Search code examples
cpointerspointer-arithmetic

Referencing a struct member with pointer arithmetic


I've got a struct definition,

struct liste{
    unsigned int size;
    unsigned int capacity;
    char* data;
};

and an instance,

struct liste lst = {3, 4, "hi"};

and what I'm trying to do is get the data member without directly calling lst.data. So far I've been able get a pointer, dataC ;

char* dataC = (char *) ((char *)&lst + 2 * sizeof(unsigned int));

whereby printing dataC and &lst.data as pointers gives the same output. I thought dereferencing dataC and casting the result to a char * would yield a pointer identical lst.data but I get a segfault.

Is there something I'm missing??


Solution

  • According to your code, dataC does not store the address of the data "hi", but the address of the pointer of lst.data. You can see the code below. dataC is the address of lst.data. *dataC is the address of the string "hi", the same as lst.data.

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include<stdint.h>
    struct liste{
        unsigned int size;
        unsigned int capacity;
        char *data;
    };
    
    int main()
    {
        
        struct liste lst = {3, 4,"hi"};
        char **dataC = (char **) ((char *)&lst + 2 * sizeof(unsigned int));
        printf("datac = %s\n",(*dataC));
    
    }