I am trying to understand when exactly a variable get memory in C when declared inside main function . I found a similar question When does memory gets allocated for a variable in c? here. It mentions that there is no hard and fast rule when memory will be allocated. But I am trying to understand my case specifically . I just declared some variable of different types but did not initialise any one of them. I just tried to print the sizeof those variable and I was able to print it. My question is whether memory is already allocated as I am able to print the size of the variable which I declared ?
#include <stdio.h>
int main()
{
int x;
int *y;
float a;
float *b;
double a1;
double *b1;
char c;
char *c1;
printf("sizeof of x = %d \n",sizeof(x));
printf("size of *x = %d \n",sizeof(*y));
printf("sizeof of a = %d \n" ,sizeof(a));
printf("sizeof of *b = %d \n" ,sizeof(*b));
printf("sizeof of a1 = %d \n" ,sizeof(a1));
printf("sizeof of *b1 = %d \n" ,sizeof(*b1));
printf("sizeof of c = %d \n" ,sizeof(c));
printf("sizeof of *c = %d \n" ,sizeof(*c));
}
Output:
sizeof of x = 4
size of *x = 4
sizeof of a = 4
sizeof of *b = 4
sizeof of a1 = 8
sizeof of *b1 = 8
sizeof of c = 1
sizeof of *c = 1
I have some follow up questions as well. Why there is a difference in the sizeof pointer variable based upon data type ? At the end, any pointer varaible will contain an address which is an integer.
y
is the pointer,*y
is the data the ponter pints to.sizeof(int)
which isn't a variable but a type. Note that "any pointer variable will contain an address which is an integer" is incorrect. All computer data is bits, but a pointer is not an integer norint
and your%d
is undefined behaviour. Please use%zu
for typesize_t
.