Search code examples
arrayscpointersmultidimensional-arraydereference

why does my array of strings assignment not work with pointers?


I have a struct that stores 5 char * pointers

struct x {

       char *arr[5];
};

I allocated memory for the struct using malloc()

struct x *str = malloc(sizeof(struct x));

However when i try to initialize arr with a value (namely a read only string-literal) it gives me an error

error: expected identifier before ‘(’ token
   13 |     (*str).(*(arr+0)) = "hello";
                   ^

here is my initialization

(*str).(*(arr+0)) = "hello";

i know i could do it like this

str->arr[0] = "hello"

but i would like to understand how array of strings work, so i have used pointers and firstly dereferenced str-> and changed it to (*str).

Also since arr[0] works in the initialization str->arr[0] = "hello" and i know that arr[0] is equivalent to *(arr+i) where i is a array cell, i though that this would work in (*str).(*(arr+0)) = "hello"; but it does not.

Why is this and how are arrays of strings actually working behind the scenes?


Solution

  • The structure has the data member arr.

    struct x {
    
           char *arr[5];
    };
    

    So you have to write accessing the data member using the operator . or -> for example like

    *( (*str).arr + 0) = "hello";
    

    that is the same as

    *(*str).arr = "hello";
    

    or

    *str->arr = "hello";
    

    Or

    str->arr[0] = "hello";
    

    That is member access operators are defined like

    postfix-expression . identifier 
    postfix-expression -> identifier
    

    while you are trying to use an expression that is not an identifier.

    Using your approach to access ant element of the array you can write

    *( (*str).arr + i) = "hello";
    

    or

    *( str->arr + i) = "hello";
    

    That is at first you need to get the array designator like

    ( *str ).arr
    

    or

    str->arr
    

    and then you can use the pointer arithmetic with the obtained array.