0

I am a newbie to C,

My Problem is the following code,

int Max[10],*New_Max;
int length=5;
New_Max=(int)malloc(sizeof(int)*length));
printf("sizeof(Max)=%d,sizeof(New_Max)=%d",sizeof(Max),sizeof(New_Max));`

Output:

sizeof(Max)=40,sizeof(New_Max)=4

I Expect sizeof(New_Max) to be 20, but it prints as 4.

Can anyone explain the reason for it.

Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
Vijay Manohar
  • 473
  • 1
  • 7
  • 22

2 Answers2

2

The following line allocates memory to what New_Max is pointing.

New_Max=(int)malloc(sizeof(int)*length));

And, the following line grabs the info about what a pointer size is :

sizeof(New_Max)

So, the size of what pointer is pointing and its own size are two different things. That's why you are getting size of New_Max to be 4.

learner
  • 4,614
  • 7
  • 54
  • 98
1

You are making wrong assumption, that sizeof behaves in the same way for both types of memory allocation. There is fundamental difference between array and pointer and how it relates to sizeof. If you provide it with array, like here:

int Max[10];
size_t size = sizeof(Max);

then you will get overall size, that is number of elements multiplied by size of each element, that is:

10 * sizeof(Max[0])

On the other hand, for pointers, it results into size of pointer itself, not taking any elements into account, thus what you get is just sizeof(int *). It does not matter if it points to NULL or some array object, the size would be the same.

Note that, the proper format specifier for sizeof is %zu, not the %d.

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137