Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find malloc() array length in C? [duplicate]

Tags:

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)

I'm learning how to create a dynamic array in C, but have come across an issue I can't figure out.

If I use the code:

int num[10]; for (int i = 0; i < 10; i++) {     num[i] = i; } printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0])); 

I get the output:

sizeof num = 40 sizeof num[0] = 4 

This is what I'd expect to happen. However if I malloc the size of the array like:

int *num; num = malloc(10 * sizeof(int)); for (int i = 0; i < 10; i++) {     num[i] = i; } printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0])); 

Then I get the output:

sizeof num = 8 sizeof num[0] = 4 

I'm curious to know why the size of the array is 40 when I use the fixed length method, but not when I use malloc().

like image 411
GCBenson Avatar asked Dec 22 '12 16:12

GCBenson


People also ask

How do you get the size of the allocated array?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

How do you find the length of an array in C?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.

Can you malloc an array in C?

In c programming, the array is used to store a range of values of the same data type and it occupies some space in memory which can be either static or dynamic. The malloc is a function used in the c programming for dynamic memory allocation.


2 Answers

In the second case, num is not an array, is a pointer. sizeof is giving you the size of the pointer, which seems to be 8 bytes on your platform.

There is no way to know the size of a dynamically allocated array, you have to save it somewhere else. sizeof looks at the type, but you can't obtain a complete array type (array type with a specified size, like the type int[5]) from the result of malloc in any way, and sizeof argument can't be applied to an incomplete type, like int[].

like image 175
effeffe Avatar answered Oct 07 '22 17:10

effeffe


Arrays are not pointers (the decay to pointers in some situations, not here).

The first one is an array - so sizeof gives you the size of the array = 40 bytes.

The second is a pointer (irrespective of how many elements it points to) - sizeof gives you sizeof(int*).

like image 22
Luchian Grigore Avatar answered Oct 07 '22 17:10

Luchian Grigore