Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct pointer accessing fields

Tags:

c

pointers

struct

I've read that if we have a pointer to a struct type object we can't access the object field by using the asterisk (*) but we need to use this -> (like an arrow sign).

Now although I read about it I didn't understand why we can't use the asterisk, I'll try to provide a code example and a picture of how I visualize a struct in memory to help you understand what is preventing me from understanding this topic.

Okay, so here's our code :

#include <stdio.h>

typedef struct MyStruct
{
    char c1;
    char c2;
} MyStruct;

int main()
{
    MyStruct s1; // Let's assume s1's address is 0x34A
    s1.c1 = 'A';
    s1.c2 = 'B';
    printf("s1 c1 is %c and c2 is %c.\n", s1.c1, s1.c2);

    MyStruct *p = &s1; // Declaring our pointer to point to s1 address, so p points to 0x34A
    printf("s1 c1 is %c and c2 is %c.\n", p->c1, p->c2); // I know this is the valid way
    printf("s1 c1 is %c.\n", *p.c1); // I don't understand why this would be invalid
    return 0;
}

Now let me try to explain why I don't understand why this syntax is invalid. So p is pointing to the address of s1 which is 0x34A and as I see it this is how I see s1 in memory:

enter image description here

So what I imagine it as in memory is that s1 has it's own address of course which in our example is 0x34A and it points to c1 address in memory which is followed up by c2 address. So when I do this :

printf("s1 c1 is %c.\n", (*p.c1)++, *p.c2);

I think of it as I'm accessing the value that is inside the pointer address by our pointer so we're accessing the value which is c1.

But as I said it's invalid and I just breaking my head trying to understand why, I've tried to read about it but couldn't really put the finger on the answer that will satisfy me on why really, so I've provided the code example and the picture so you could get into my head and try and see why I'm thinking wrong here.

like image 662
Akes55 Avatar asked Sep 09 '14 15:09

Akes55


1 Answers

*p.c1 is parsed as *(p.c1) not (*p).c1.

So when you do *(p.c1), you attempt to use the dot operator on a pointer, which fails.

like image 115
Bill Lynch Avatar answered Sep 18 '22 23:09

Bill Lynch