你传入两个int和一个指针(第三个参数)的地址,你应该接受前两个参数中的指针(一个*
)为int和第三个参数的指针为int的指针(二**
):
void load(int* n, int* x, int **arr){
// ^ ^one* ^two **
*n = 10;
*x = 9;
}
在负载功能,您可以将值分配给*n
和*x
,因为这两个指向有效的内存地址,但你不能做**arr = 10
只是因为arr
不指向任何内存(指向NULL),所以第一你有t o首先为*arr
分配内存,不喜欢:
void load(int* n, int* x, int **arr){
*n = 10;
*x = 9;
*arr = malloc(sizeof(int));
**arr = 10;
}
是在C语言编码本文档是有用的,这是一个好的做法呢?
是
,但有时我的文档喜欢在以下方面,我的函数参数:
void load(int n, // is a Foo
int x, // is a Bar
int **arr){ // do some thing
// something
}
参考:for document practice
编辑如你评论,不喜欢以下我正在写,它不会给出任何错误/因为malloc()
。
#include<stdio.h>
#include<stdlib.h>
void load(int* n, int* x, int **arr){
*n = 10;
*x = 9;
*arr = malloc(sizeof(int));
**arr = 10;
printf("\n Enter Three numbers: ");
scanf("%d%d%d",n,x,*arr);
}
int main(){
int n = 0, x = 0;
int *arr = NULL;
load(&n, &x, &arr);
printf("%d %d %d\n", n, x, *arr);
free(arr);
return EXIT_SUCCESS;
}
编译并执行,如:
~$ gcc ss.c -Wall
:~$ ./a.out
Enter Three numbers: 12 13 -3
12 13 -3
作为评论由OP:
“从无效皈依无效*为int *” 时我更改为ARR = malloc的( sizeof(int)(* n));
syntax of malloc():
的malloc()返回void*
和*arr
类型是int*
就是这个原因编译消息,因为不同的类型:"Invalid convertion from void* to int*"
但我避免铸造时的malloc(),因为:Do I cast the result of malloc?(阅读Unwind的回答)
请查看关于[引用调用]的解释(http://en.wikipedia.org/wiki/Call-by-reference#Call_by_reference) – Bechir 2013-04-06 13:11:58