33

I am trying to access items in an array of structs and print the structs fields as follows

printList(Album *a, int numOfStructs)
{
    int i;
    int j;

    for(i = 0; i < numOfStructs; i++)
    {
         printf("number%d\n:", i+1);
         printf("%s", a[i]->field2);
         printf("%s", a[i]->field2);
         printf("%d", a[i]->field3);

         for(j = 0; j < a[i]->numOfStrings; j++)
         {
             printf("%s", a[i]->strings[j]);
         }
         printf("\n");
    }
}

but I get loads of errors as such

invalid type argument of '->'

What am I doing wrong with this pointer?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
some_id
  • 29,466
  • 62
  • 182
  • 304

2 Answers2

50

a is of type Album* which means that a[i] is of type Album (it is the ith element in the array of Album object pointed to by a).

The left operand of -> must be a pointer; the . operator is used if it is not a pointer.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
13

You need to use the . operator. You see, when you apply a * to a pointer, you are dereferencing it. The same goes with the []. The difference between * and [] is that the brackets require an offset from the pointer, which is added to the address in the pointer, before it is dereferenced. Basically, these expressions are identical:

*ptr == ptr[0]
*(ptr + 1) == ptr[1]
*(ptr + 2) == ptr[2]

To connect to your question: Change a[i]->field2 and a[i]->field3 to a[i].field2 and a[i].field3.

Jörgen Sigvardsson
  • 4,839
  • 3
  • 28
  • 51
  • Thanks. different parts of my program need -> and others need . ? I just started with C and as soon as I think I understand pointers, I realize I have no clue. :( When I try the following fgets(&(tempAlbum->field1),MAXCHARACTERS, stdin); I get warning: passing argument 1 of 'fgets' from incompatible pointer type – some_id Feb 13 '11 at 07:57