Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is mallocing equivalent to pointer with a specified array size

Tags:

c

pointers

I've read various tutorials on pointers, and I now come with a question,

is this:

char *input = malloc(sizeof(char)*24);

the same as

char *input[24];

I was under the impression that the malloc will also create my space on the heap with 24 slots. Usually, I see char input[24], but the char *input[24] I figured was a simpler way than mallocing.

Thanks!

like image 409
markfiel Avatar asked Dec 16 '22 13:12

markfiel


2 Answers

No, they are not the same.

char *input = malloc(sizeof(char)*24);

will allocate a block of 24 char's on the heap and assign a pointer to the start of that block to input. (technically you are just telling it to allocate x number of bytes where x is 24 times the size, in bytes, of each char)

char *input[24];

will create an array of 24 char pointers on the stack. These pointers will not point to anything (or garbage on init) as you have it written.

For the second example, you could then take each pointer in the array input and allocate something for it to point to on the heap. Ex:

char *input[NUM_STRS];
for( int i = 0; i < NUM_STRS; i++ )
    {
    input[i] = malloc( MAX_STR_LEN * sizeof(char) );
    }

Then you would have an array of character pointers on the stack. Each one of these pointers would point to a block of characters on the heap.

Keep in mind, however, that things on the stack will be popped off when the function exits and that variable goes out of scope. If you malloc something, that pointer will be valid until it is freed, but the same is not true of an array created on the stack.

EDIT: Based on your comment, here is an example of making 24 character pointers on the heap and allocating space for them to point to:

#define NUM_STRS 24
#define MAX_STR_LEN 32
char **input = malloc( sizeof(char *) * NUM_STRS );
for( int i = 0; i < NUM_STRS; i++ )
    {
    input[i] = malloc( sizeof(char) * MAX_STR_LEN );
    }

Please keep in mind that with this example you will have to free each pointer in input, and then input itself at the appropriate time to avoid leaking memory.

like image 149
Gavin H Avatar answered Dec 21 '22 23:12

Gavin H


These are not the same at all.

char *input = malloc(sizeof(char)*24);

This allocates enough memory to hold 24 char, and assigns the address to input (a pointer). This memory is dynamically-allocated, so it needs to be released at some point with an appropriate call to free().

char *input[24];

This declares input to be an array of 24 pointers. This has automatic storage, which means you do not need to free it. (However, you may need to free the things being pointed to by each of the pointers, but that's a different matter!)

like image 20
Oliver Charlesworth Avatar answered Dec 22 '22 00:12

Oliver Charlesworth