Mr Cherno
Mr Cherno

Reputation: 315

Dynamic Memory Allocation for Arrays in C

So I'm trying to create a dynamic array in C, using malloc, but for some reason it's not working out. Here's my code:

    int* test = (int*) malloc(20 * sizeof(int));
    printf("Size: %d\n", sizeof(test));

The console outputs 8 when I run this code, although it ideally should output 80, I believe, since the size of an int is 4, and I'm creating 20 of them. So why isn't this working? Thanks for any help. :)

Upvotes: 3

Views: 558

Answers (3)

maverick
maverick

Reputation: 19

if you try to print value of sizeof (&test), you will get 80 (20 * 4). &test is of type int (*) [20].

I hope it clarifies your doubt.

Upvotes: 0

Sandesh Kobal
Sandesh Kobal

Reputation: 920

Here sizeof operator is giving you the number of bytes required to store an int*
i.e. it is equivalent to sizeof(int*);
Depending on the compiler it may give you 4 or 8

In C its programmers job to keep track of number of bytes allocated dynamically.

Upvotes: 3

Charles Salvia
Charles Salvia

Reputation: 53289

The sizeof operator is returning the size of an int*, which is just a pointer. In C, when you allocate memory dynamically using malloc, the call to malloc returns a pointer to the newly allocated block of memory (usually on the heap.) The pointer itself is just a memory address (which usually only takes up 4 or 8 bytes on most modern systems). You'll need to keep track of the actual number of bytes allocated yourself.

The C language will only keep track of buffer sizes for statically allocated buffers (stack arrays) because the size of the array is available at compile time.

int test[100];
printf("Sizeof %d\n", sizeof(test))

This will print a value equal to 100 * sizeof(int) (usually 400 on most modern machines)

Upvotes: 8

Related Questions