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;
} 
1

4 Answers 4

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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)

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.