[英]How to pass argument array pointer in function?
I have this code: 我有以下代码:
// *** foo.c ***
#include <stdlib.h> // malloc
typedef struct Node {
char (*f)[20];
//...
} Node;
int function(char f[30][20]){
// Do some stuff with f...
}
int main(){
Node * temp = (Node*)malloc(sizeof(Node));
function(temp->f[20]);
}
I would like to pass temp->f
array pointer to function, but on compile I get these errors: 我想将
temp->f
数组指针传递给函数,但是在编译时出现以下错误:
$ gcc foo.c -o foo
foo.c: In function ‘main’:
foo.c:16:5: warning: passing argument 1 of ‘function’ from incompatible pointer type [enabled by default]
function(temp->f[20]);
^
foo.c:10:5: note: expected ‘char (*)[20]’ but argument is of type ‘char *’
int function(char f[30][20]){
^
How can I fix it? 我该如何解决?
expected 'char (*)[20]' but argument is of type 'char *
Change the way you call the function to: 将调用函数的方式更改为:
function(temp->f);
Also: 也:
When you pass an array "f" as argument, you are passing its first item ADDRESS (as arrays are pointers) But when you pass f[20] as argument, you are passing the VALUE of the 20th element of f 当您将数组“ f”作为参数传递时,您将传递其第一项ADDRESS(因为数组是指针),但是当您将f [20]作为参数传递时,您将传递f的第20个元素的值
So, if you pass (f) (or temp->f in your case) you are passing an address and the destination shall be "char*" type to receive. 因此,如果您传递(f)(或者您的情况是temp-> f),则您传递的是地址,并且目的地应为“ char *”类型以进行接收。
And if you pass f[20] (or temp->f[20]) you are passing a value and the destination shall be "char" type 并且如果您传递f [20](或temp-> f [20]),则您传递的是值,并且目的地应为“ char”类型
If you want to receive the address of the 20th item, you should pass &(f[20]) ( or &(temp->f[20]) ) 如果要接收第20个项目的地址,则应传递&(f [20])(或&(temp-> f [20]))
Just to clarify: "f" is equivalent to "&(f[0])", as both represents the address of the first item 需要澄清的是:“ f”等效于“&(f [0])”,因为两者都代表第一项的地址
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.