Search code examples
arrayscpointersimplicit-conversionpointer-arithmetic

Traversing structs using pointer++


This might be a dumb question but I'm just learning C.

I have declared:

#include <stdio.h>
#include <string.h>
#include <stdlib.h> 

typedef struct STRUCTURE{
    char name[30];
}STRUCT;

int main(void){
    STRUCT struct1[30] // declaring 30 structs.
    STRUCT *pointer;
    pointer = &struct1;
    return 0;
}

Now, if I wanted to reference to specific struct (of the 30 structs) I could do it like:

&struct[0] // first struct's memory location
&struct[1] // second struct's memory location 
...
&struct[i] // where i = 0, 1, 2, 3, 4, 5 ... 29

But how would I do it using the pointer?

I thought by incrementing the pointer I could traverse the structs:

pointer++

But I can't seem to be getting from struct1[i] to struct1[i+1] with pointer++


Solution

  • For starters this assignment

    pointer = &struct1;
    

    is incorrect. The expression in the right side of the assignment &struct1 has the pointer type STRUCT ( * )[30] while the operand in the left side has the pointer type STRUCT * and there is no implicit conversion from one type to another.

    Instead you need to write

    STRUCT struct1[30] // declaring 30 structs.
    STRUCT *pointer;
    pointer = struct1;
    

    In this case the array designator struct1 is implicitly converted to a pointer to its first element and the pointer pointer will point to that first element of the array struct1 and using the pointer arithmetic you can access any element of the array.

    For example, to output strings stored in the data member name of elements of the array (provided that they are initialized) using for loop you can write

    for ( STRUCT *p = struct1; p != struct1 + 30; ++p )
    {
        printf( "%s ", p->name );
    }
    putchar( '\n' );
    

    Or instead of using the magic number 30 you could introduce a named constant as for example

    enum { N = 30 };
    STRUCT struct1[N];
    

    and the n to write the loop like

    for ( STRUCT *p = struct1; p != struct1 + N; ++p )
    {
        printf( "%s ", p->name );
    }
    putchar( '\n' );
    

    In this case if you will want to change the size of the array it will be enough to change the program only in one place in the enumeration declaration.

    Pay attention to that the expression

    pointer[i] is equivalent to the expression *( pointer + i] ). And the expression &pointer[i] is correspondingly equivalent to pointer + i.