您正在传递两个 int 和一个指针(第三个参数)的地址,您应该在指向 int 的指针(一个*
)中接收前两个参数,并在指向 int 的指针(两个**
)的指针中接收第三个参数:
void load(int* n, int* x, int **arr){
// ^ ^ one* ^ two **
*n = 10;
*x = 9;
}
在 load 函数中,您可以将值分配给*n
and*x
因为两者都指向有效的内存地址,但您不能**arr = 10
仅仅因为arr
不指向任何内存(指向 NULL)所以首先您必须首先为 分配内存*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
}
参考资料:供文档练习
编辑正如您评论的那样,请像下面我写的那样,它不会给出任何错误/因为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 评论的那样:
“从 void* 到 int* 的无效转换”当我将其更改为arr = malloc(sizeof(int) (*n));
malloc() 的语法:
void *malloc(size_t size);
malloc() 返回void*
和*arr
类型是int*
编译器消息的原因,因为类型不同:"Invalid convertion from void* to int*"
但是我避免在 malloc() 时进行强制转换,因为:我会强制转换 malloc 的结果吗?(阅读 Unwind 的回答)