Thread: Array of struct

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0

    Array of struct


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct
    {
       int x;
       int y;
       char *str1;
       char *str2;
    }Struct1;
    
    
    void processFromStruct1(Struct1 content[])
    {
        printf("%s", content[1].str1);
    }
    
    int main()
    {
        Struct1 mydata[]=
        { {1,1,"black","cat"},
          {4,5,"red","bird"},
          {6,7,"brown","fox"},
        };
    
        processFromStruct1(&mydata);
    
        return 0;
    }
    I'm getting the error:

    Code:
    test.c: In function ‘main’:
    test.c:26:5: aviso: passing argument 1 of ‘processFromStruct1’ from incompatible pointer type
    test.c:13:6: nota: expected ‘struct Struct1 *’ but argument is of type ‘struct Struct1 (*)[3]’
    What is wrong with my code?
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Location
    Saint-Petersburg, Russia
    Posts
    236
    Rep Power
    28
    remove the "&" (ampersand) before "mydata". Array is the pointer itself, you need not take its address once more.
    CodeAbbey - programming problems for novice coders
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,086
    Rep Power
    2222
    To offer a broader explanation, an array name is generally the same thing as a pointer to the first element of the array; ie:

    mydata == &mydata[0]

    Therefore, your function call should have been either
    Code:
        processFromStruct1(&mydata[0]);
    or
    Code:
        processFromStruct1(mydata);
    with the latter being preferred. As you can see, writing &mydata (as opposed to &mydata[0]) added an extra level of indirection which doesn't even make any sense.

    The equivalence of array names and pointers can only be taken so far. The main difference is that you cannot change where an array name points to. So while you can assign a different address to a pointer, you cannot do the same to an array name. And while you can increment or decrement a pointer, you cannot do the same to an array name. Other than that (unless I forgot one), you can safely treat an array name as a pointer and vice versa (eg, use array indexing notation on a pointer).

IMN logo majestic logo threadwatch logo seochat tools logo