3

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. :)

2
  • 1
    remember to check the return value of malloc always, check the documentation for that.... Commented May 29, 2013 at 0:07
  • 3
    Sidenote: when programming in C please do not cast the return value of malloc. Commented May 29, 2013 at 0:10

3 Answers 3

8

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)

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

3 Comments

Thanks for the reply. So how can I get the size of a dynamic array?
@Mr Cherno, you can't get it using standard ANSI-C. You have to simply keep track of it yourself using a separate variable. (You know you allocated a buffer equal to the size of 20 * sizeof(int)).
@CharlesSalvia, one pedantic point, the size of dynamically allocated memory is kept track of otherwise you would have to specify the size when you call free() stackoverflow.com/questions/1518711/…
3

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.