1

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?

3
  • 1
    Please show us the error. Commented May 18, 2017 at 12:41
  • expected 'char (*)[20]' but argument is of type 'char *' Commented May 18, 2017 at 12:45
  • 1
    @uninopkn Which in turn should lead you to think "what char*, I passed an array pointer. Or wait... maybe I didn't..." Commented May 18, 2017 at 12:49

2 Answers 2

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

Change the way you call the function to:

function(temp->f);

Also:

Sign up to request clarification or add additional context in comments.

3 Comments

How is that declaration any different from the original?
@Lundin you are right, I began writing something else but changed my mind.
Sorry, I didn't know we weren't supposed to do what I did in the edit. Live and learn :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.