Search code examples
cpointersallocation

Memory allotment in C


 #include <stdio.h>

 main(){
 int *px;
 int i =1;
 float f = 0.3;
 double d = 0.0005;
 char c = '*';

 px = &i;
 printf("Values: i=%i f=%f d=%f c=%c \n\n", i ,f, d,c);
 printf("Addresses: &i=%X &f=%X &d=%X &c=%X\n\n", &i, &f, &d, &c);
 printf("Pointer values: px=%X px+1=%X px+2=%X px+3=%X\n\n",px,px+1,px+2,px+3);

 }

variables are allotted memory address as below

Values:i=1 f=0.300000 d=0.00500 c=*

Addresses: &i=FFF4 &f=FFF0 &d=FFE8 &c=FFE7

Pointer values: px=FFF4 px+1=FFF6 px+2=FFF8 px+3=FFFA

Why is the memory allotted to char variable first?


Solution

  • Local variables are allocated on the stack and the stack grows towards smaller values. So the highest address is allocated first and the lowest last and therefore the last local variable has the lowest address in the most obvious order to allocate addresses.

    This however isn't necessarily guaranteed behaviour as the compiler is free to arrange storage for local variables on the stack in whatever way it deems to be optimal.