Search code examples
cpointersmallocdynamic-memory-allocationallocation

What does allocating memory of size char * do?


char    *str;
str = malloc(sizeof(char) * 5);

This code allocates 5 consecutive slots of memory to the variable str, which is of type char *.

char    *str;
str = malloc(sizeof(char *) * 5);

This is supposed to allocate 5 times the memory of an array of char. But since an array of char has no size until we declare it, what does this statement actually do?


Solution

  • The following code

    char **str = malloc(sizeof(char *) * 5);
    

    allocates memory for 5-consecutive elements of type char *, i.e.: pointer to char.

    You could then allocate N-consecutive elements of type char and assign their addresses to these pointers:

    for (int i = 0; i < 5; i++)
       str[i] = malloc(sizeof(char) * N));