0
#include <stdio.h>
int main()
{
 int *p=(int*)malloc(sizeof(int));
 *p=0XABCDE012;
 printf("p=%X",*p);
 printf("\n");
 unsigned char *q=p;  #pointer pointing to pointer
 printf("q=%X\n",*(q++));
 printf("q=%X\n",*(q++));
 printf("q=%X\n",*(q++));
 printf("q=%X\n",*(q++));
 return 0;
}

this is pointer pointing to pointer.but the pointer pointing to pointer goes backwards. why is q going backwards?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

1

TL;DR - Read about endianness. Most likely, you're on a little-endian system. You can check that yourself by running a short program.

Regarding the use of character pointer to point to another type, and use that to access the value, quoting C11, chapter 6.3.2.3/P7

...When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.

So, if you're on a little endian system, the values are stored like

  +----------+-----------+-----------+-----------+
  |          |           |           |           |
  |   12     |    E0     |    CD     |    AB     |
  |          |           |           |           |
  +----------+-----------+-----------+-----------+
1000        1001         1002        1003         1004

  ^
  |
  q

Assuming, the starting address is 1000. So, q initially points to address 1000, and with every increment, it moves 1 byte, and when read, returns the value stored there.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261