0

i run the following code but it kept printing "4"

why its printing "4" and not "12"? and can I use malloc and then sizeof?(if i can then how)

#include<stdio.h>
int main()
{
    int arr1[3]={1,2,3};
    int *arr2=arr1,i;
    printf("%d",sizeof(arr2));
    return 0;
} 
haccks
  • 104,019
  • 25
  • 176
  • 264
  • Check out this link on how to [determine the size of an array](http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c) – John Odom Dec 24 '14 at 15:10

4 Answers4

8

Pointers are not arrays. arr2 is a pointer to int. sizeof(arr2) will return size of pointer. To print size of an array, the operand of sizeof must be of an array type:

printf("%u",sizeof(arr1));  

can I use malloc and then sizeof?

No. There is no portable way to find out the size of a malloc'ed block. malloc returns pointer to the allocated memory. sizeof that pointer will return size of the pointer itself. But you should note that, there is no need to use sizeof when you allocate memory dynamically. In this case you already know the size of array. (In case of char array use strlen).

Further reading: c-faq: Why doesn't sizeof tell me the size of the block of memory pointed to by a pointer?

haccks
  • 104,019
  • 25
  • 176
  • 264
6

arr2 is a pointer and you are printing sizeof(pointer)

sizeof(arr1) will give you sizeof array which might give you 12.(Given your integer is 4 bytes)

Gopi
  • 19,784
  • 4
  • 24
  • 36
6
sizeof(arr2)

would print the size of pointer as it's a int*. However, if you try sizeof(arr1), it would print

sizeof(element_type) * array_size

i.e size of array. Remember that it's not taking into account how many elements are there in array. It would just consider how many elements can array store.

ravi
  • 10,994
  • 1
  • 18
  • 36
3

It's printing 4 because arr2 is a pointer, and the size of a pointer is 4 bytes in 32bit architectures. You can't know the size of a dynamically allocated array ( array allocated with malloc ) given just a pointer to it.