Gavin
Gavin

Reputation: 2824

Pointer precedence and dereferring in C

struct student{
    int age;
    char *name;
};
struct student b[3] = { 30, "Peter", 40, "Mary", 50, "John" };
struct student *p = b;



int main()
{
    printf("%d\n", ++p->age);
    printf("%s\n", (*p).name);
    printf("%c\n", *p->name-1);
    printf("%c\n", *++p->name);
    printf("%c\n", *p++->name);
    printf("%c\n", *(++p)->name);
}

I am having a hard time trying to figure out how each of the statement work, could anyone give a break down of what was done?

1: ++p->age isn't it suppose to be increase p and then access the member age?

Upvotes: 1

Views: 90

Answers (1)

Spikatrix
Spikatrix

Reputation: 20244

printf("%d\n", ++p->age);

p->age is executed first. Then, the prefix increment operator(++) increases the value by one and this value is printed(31).

printf("%s\n", (*p).name);

Here, (*p).name is the same as p->name. This prints Peter.

printf("%c\n", *p->name-1);

Firstly, p->name executes which gives Peter. Applying the dereference operator gives the first character of Peter which is P. Subtracting one from P gives us O and this is the character that gets printed.

printf("%c\n", *++p->name);

Here, p->name executes first and gives Peter. When this is incremented, it gives eter. When the dereference operator is applyed, we get the first character of eter which is e. This is the character that gets printed.

printf("%c\n", *p++->name);

Here, ++ gets executed first. Since it is the postfix increment operator, the original value is returned. Then, -> executes and this gives us eter(Since it was already incremented in the previous printf). When the * operator is applyed here, we get e. This is printed.

printf("%c\n", *(++p)->name);

Here, p is incremented. Now, it points to b[2](It was incremented once in the previous printf). Then, -> executes which gives John. Applying the * operator, we get J and this is printed.

Reading about operator precedence would be handy.

Upvotes: 3

Related Questions