0

I have written following program .

#include<stdio.h>
#include<stdlib.h>
struct Test
{
   int count;
};

void main()
{
   struct Test *ptr;
   struct Test test;

   ptr = malloc(sizeof(struct Test));
   if ( ptr)
   {
      ptr->count = 123;
      test.count  = 456;

      printf("count : %d ",(*ptr).count);
      printf("count : %d ",(&test)->count);
   }
   else
   {
      printf(" malloc failed \n");
   }
}

output of the program: count : 123 count : 456

Can anyone please explain how to represent (*ptr).count and (&test)->count in this code and how it is working ?

3 Answers3

1

(&test)->count is equivalent to (*(&test)).count. For more, you can glance at Arrow operator (->) usage in C

1

Well, a->x is basically short for (*a).x, it's just that working with pointers to structures is quite common in C, so the syntax has some extra sugar there to make it simpler. Dropping the need for parentheses is really helpful in my opinion.

Basically you use . when the value on the left-hand side is of struct type, and -> when it is the address of a structure.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

So ptr and test are 2 vars of different types. ptr is a pointer to struct Test, whereas test just is that struct. As per usual, you access values of pointers through indirection (denoted by -> as opposed to .).

To reassign a pointer, first you have to dereference the pointer, which is done using the * operator, hence: (*ptr).count is basically read as: get the value ptr points to and use it. The entire expression is basically the long-form of ptr->count.

(&test)->count on the other hand is a bit silly. You have an object on stack, but rather than accessing its fields quickly and cheaply, you are getting the memory address (which is what & does - it's the "address of" operator), and creating an in-place pointer. Then you are getting the value stored in count using indirection. The expression (&test)->count reads as: "get me a pointer to test, and using that pointer, access the field count". It's equivalent to *(&test).count A bit redundant, then.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149