alryosha
alryosha

Reputation: 743

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:

$ 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?

Upvotes: 1

Views: 96

Answers (2)

Marievi
Marievi

Reputation: 5011

expected 'char (*)[20]' but argument is of type 'char *

Change the way you call the function to:

function(temp->f);

Also:

Upvotes: 4

Gustavo Laureano
Gustavo Laureano

Reputation: 566

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

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.

And if you pass f[20] (or temp->f[20]) you are passing a value and the destination shall be "char" type

If you want to receive the address of the 20th item, you should pass &(f[20]) ( or &(temp->f[20]) )

Just to clarify: "f" is equivalent to "&(f[0])", as both represents the address of the first item

Upvotes: 1

Related Questions