NOTE: My examples are not checking for NULL returns from malloc()... you really should do that though; you will crash if you try to use a NULL pointer.

First you have to create an array of char pointers, one for each string (char *):

char **array = malloc(totalstrings * sizeof(char *));

Next you need to allocate space for each string:

int i;
for (i = 0; i < totalstrings; ++i) {
    array[i] = (char *)malloc(stringsize+1);
}

When you're done using the array, you must remember to free() each of the pointers you've allocated. That is, loop through the array calling free() on each of its elements, and finally free(array) as well.

Answer from mah on Stack Overflow
Top answer
1 of 5
32

NOTE: My examples are not checking for NULL returns from malloc()... you really should do that though; you will crash if you try to use a NULL pointer.

First you have to create an array of char pointers, one for each string (char *):

char **array = malloc(totalstrings * sizeof(char *));

Next you need to allocate space for each string:

int i;
for (i = 0; i < totalstrings; ++i) {
    array[i] = (char *)malloc(stringsize+1);
}

When you're done using the array, you must remember to free() each of the pointers you've allocated. That is, loop through the array calling free() on each of its elements, and finally free(array) as well.

2 of 5
14

The common idiom for allocating an N by M array of any type T is

T **a = malloc(N * sizeof *a);
if (a)
  for (i = 0; i < N; i++)
    a[i] = malloc(M * sizeof *a[i]);

As of the 1989 standard, you don't need to cast the result of malloc, and in fact doing so is considered bad practice (it can suppress a useful diagnostic if you forget to include stdlib.h or otherwise don't have a prototype for malloc in scope). Earlier versions of C had malloc return char *, so the cast was necessary, but the odds of you having to work with a pre-1989 compiler are pretty remote at this point. C++ does require the cast, but if you're writing C++ you should be using the new operator.

Secondly, note that I'm applying the sizeof operator to the object being allocated; the type of the expression *a is T *, and the type of *a[i] is T (where in your case, T == char). This way you don't have to worry about keeping the sizeof expression in sync with the type of the object being allocated. IOW, if you decide to use wchar instead of char, you only need to make that change in one place.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ how-to-create-a-dynamic-array-of-strings-in-c
How to Create a Dynamic Array of Strings in C? - GeeksforGeeks
July 23, 2025 - To create a dynamic array of strings in C, we can use the concept of double pointer and dynamic memory allocation. The double pointer is the pointer that stores the memory address of another pointer.
Discussions

c - How to dynamically allocate memory space for a string and get that string from user? - Stack Overflow
I want to read input from user using C program. I don't want to use array like, char names[50]; because if the user gives string of length 10, then the remaining spaces are wasted. If I use chara... More on stackoverflow.com
๐ŸŒ stackoverflow.com
c - dynamic memory allocation for strings - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
๐ŸŒ stackoverflow.com
c - Dynamic memory allocation for pointer arrays - Stack Overflow
I'm am trying to write a program that reads in a series of strings from a text file and stores these in an array of strings, dynamically allocating memory for each element. My plan was to store each More on stackoverflow.com
๐ŸŒ stackoverflow.com
c - Using Dynamic Memory allocation for arrays - Stack Overflow
How am I supposed to use dynamic memory allocations for arrays? For example here is the following array in which i read individual words from a .txt file and save them word by word in the array: ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 8
30

You use pointers.

Specifically, you use a pointer to an address, and using a standard c library function calls, you ask the operating system to expand the heap to allow you to store what you need to.

Now, it might refuse, which you will need to handle.

The next question becomes - how do you ask for a 2D array? Well, you ask for an array of pointers, and then expand each pointer.

As an example, consider this:

int i = 0;
char** words;
words = malloc((num_words)*sizeof(char*));

if ( words == NULL )
{
    /* we have a problem */
    printf("Error: out of memory.\n");
    return;
}

for ( i=0; i<num_words; i++ )
{
    words[i] = malloc((word_size+1)*sizeof(char));
    if ( words[i] == NULL )
    {
        /* problem */
        break;
    }
}

if ( i != num_words )
{
    /* it didn't allocate */
}

This gets you a two-dimensional array, where each element words[i] can have a different size, determinable at run time, just as the number of words is.

You will need to free() all of the resultant memory by looping over the array when you're done with it:

for ( i = 0; i < num_words; i++ )
{
    free(words[i]);
}

free(words);

If you don't, you'll create a memory leak.

You could also use calloc. The difference is in calling convention and effect - calloc initialises all the memory to 0 whereas malloc does not.

If you need to resize at runtime, use realloc.

  • Malloc
  • Calloc
  • Realloc
  • Free

Also, important, watch out for the word_size+1 that I have used. Strings in C are zero-terminated and this takes an extra character which you need to account for. To ensure I remember this, I usually set the size of the variable word_size to whatever the size of the word should be (the length of the string as I expect) and explicitly leave the +1 in the malloc for the zero. Then I know that the allocated buffer can take a string of word_size characters. Not doing this is also fine - I just do it because I like to explicitly account for the zero in an obvious way.

There is also a downside to this approach - I've explicitly seen this as a shipped bug recently. Notice I wrote (word_size+1)*sizeof(type) - imagine however that I had written word_size*sizeof(type)+1. For sizeof(type)=1 these are the same thing but Windows uses wchar_t very frequently - and in this case you'll reserve one byte for your last zero rather than two - and they are zero-terminated elements of type type, not single zero bytes. This means you'll overrun on read and write.  

Addendum: do it whichever way you like, just watch out for those zero terminators if you're going to pass the buffer to something that relies on them.

2 of 8
7

While Ninefingers provided an answer using an array of pointers , you can also use an array of arrays as long as the inner array's size is a constant expression. The code for this is simpler.

char (*words)[15]; // 'words' is pointer to char[15]
words = malloc (num_words * sizeof(char[15]);

// to access character i of word w
words[w][i];

free(words);
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how to dynamically allocate an array and add strings to it? (in c)
r/learnprogramming on Reddit: How to dynamically allocate an array and add strings to it? (In C)
February 17, 2022 -

Okay so basically I have a function that takes in a string and counts the lowercase tokens in it. I need to make a function that then returns an array of the lowercase tokens. I would need to use malloc to allocate enough memory for such array but I donโ€™t know how to go about doing so.

Once the array is allocated how would I put the token strings into the array?

Any help is appreciated thank you

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 62156446 โ€บ how-to-make-a-strings-array-by-using-dynamic-memory-allocation-in-c
How to make a strings array by using dynamic memory allocation in C? - Stack Overflow
#include<stdio.h> #include<stdlib.h> ... //printing for (int i = 0;i < 3;i++) { printf("\n%s", arr[i]); } free(arr); } You have to allocate memory twice....
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71982328 โ€บ c-dynamic-memory-allocation-for-an-array-of-strings-problem
C- Dynamic memory allocation for an array of strings problem - Stack Overflow
April 23, 2022 - If you're using a POSIX compliant system (LInux, macOS, BSD, basically almost anything other than Windows) or an implementation supporting The C Dynamic Memory TR, it would make this task a ton simpler. ... while(fgets(buffer, MAXCHAR, fp) != NULL) { strings = malloc(lines_count * sizeof(char *)); <<<<===== length = strlen(buffer); buffer[length] = '\0'; strings[ctrl] = malloc(length * sizeof(char)); strcpy(strings[ctrl], buffer); ctrl++; }
Top answer
1 of 3
7

First you need to understand the difference between the following three declarations. For the sake of brevity, assume N is MAX_WORD_LEN+1 to match your sizing:

char data[N];      // array of N chars
char *data[N];     // array of N char *pointers* (i.e. char *)
char (*data)[N];   // pointer to array of N chars

Remember above all else, pointers are variables that hold an "address" and are implementation-defined. Just like an int variable holds the value of an implementation integer, a pointer variable holds an implementation address.

In almost all cases, you can properly malloc() memory for a pointer type using the sizeof() operator with the underlying target dereferenced. There are some cases where this is not intuitive or easily presentable, but the following should help:

// allocates sizeof(Type) block
Type *p = malloc(sizeof(*p));

// allocates N*sizeof(Type) contiguous blocks
//  note: we'll use this style later to answer your question
Type *pa = malloc(N * sizeof(*pa));

This will work no matter what Type is. This is important, because in your case you have a pointer declared as :

char (*dict)[N];

As we already discussed above, this declares a pointer of type (pointer-to-N-chars). Note that no actual memory has been allocated yet. This is just a pointer; nothing more. Therefore, you can safely allocate a single element using the above syntax as:

// allocate single block
char (*dict)[N] = malloc(sizeof(*dict));

But this only accounts for a single entry. You need len entries, so :

// allocate 'len' contiguous blocks each N chars in size
char (*dict)[N] = malloc(len * sizeof(*dict));

Now dict is safely addressable as an array from 0..(len-1). You can copy in your data such as:

strcpy(data[0], "test");
strcpy(data[1], "another test");

So long as the source string does not exceed N-chars (including the zero-terminator), this will work correctly.

Finally, don't forget to free your allocation when finished:

free(dict);

Spoiler

myDict->dict0 =  malloc( myDict->len * sizeof(*(myDict->dict0)));
myDict->dict1 =  malloc( myDict->len * sizeof(*(myDict->dict1)));
2 of 3
0

In the declaration of the structure,

char (*dict0)[MAX_WORD_LEN+1];

means that dict0 is a pointer to a character array of MAX_WORD_LEN + 1 elements i.e. char [11].

To initialize the field of your object, you can consider an example as shown below

void createDict(struct dict* myDict)
{
    myDict->dict0 = &glbarr;
    myDict->dict1 = &glbarr;
}

where glbarr is a global array defined as

char glbarr[MAX_WORD_LEN+1];
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 133453-dynamic-memory-allocation-strings.html
Dynamic memory allocation and strings.
January 3, 2011 - Make sure you allocate enough room to store the '\0': ... string = (char*) malloc(sizeof(char)*(num_char + 1)); Also, please don't ever use gets(). It's not safe.
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ what is the point of dynamic allocation in c? (plus dont get triggered. please explain why im wrong)
r/C_Programming on Reddit: what is the point of dynamic allocation in c? (plus dont get triggered. please explain why im wrong)
August 8, 2022 -

So lets say i do int x=5; so i create a variable of 4 bytes that stores a value of 5

then i do int *y= malloc(sizeof(int)); here i created a pointer that gave me a memory location in the RAM and i can do *y=5; to store 5 in it. What exactly is the benefit of using dynamic allocation here?

plus in case of strings how do i dynamically allocate just enough memory to store name of some guy in c without knowing it before hand how long the name is?

like char name[4]; means i have an array of 5 char out of which im supposed to use 4. But here i need to make sure name is of length 4 always.

but char *name = malloc(5*sizeof(char)); dynamically allocates the same memory but i still need to make sure length of name stays 4 plus one extra for the null.

how is this implemented to take values of any length?

๐ŸŒ
StudySmarter
studysmarter.co.uk โ€บ computer science โ€บ computer programming โ€บ dynamic allocation of array in c
Dynamic Allocation of Array in C: Techniques & Examples
August 10, 2023 - Challenges and solutions in dynamic ... To dynamically allocate an array of strings in C, first allocate memory for the array of pointers using `malloc` or `calloc`, then allocate memory for each string individually....
๐ŸŒ
Programiz
programiz.com โ€บ c-programming โ€บ c-dynamic-memory-allocation
C Dynamic Memory Allocation Using malloc(), calloc(), free() & realloc()
In this tutorial, you'll learn to dynamically allocate memory in your C program using standard library functions: malloc(), calloc(), free() and realloc() with the help of examples.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc
Dynamic Memory Allocation in C - GeeksforGeeks
Dynamic memory allocation allows a programmer to allocate, resize, and free memory at runtime. Key advantages include. Memory is allocated on the heap area instead of stack. Please refer memory layout of C programs for details ยท Array size ...
Published ย  2 weeks ago
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 19263396 โ€บ dynamic-memory-allocation-for-strings-in-c
dynamic memory allocation for strings in c - Stack Overflow
May 23, 2017 - The memory for that variable would be on the stack and already "allocated" for you. That call to malloc determines what you store in that variable, not where you store that variable. ... It's only safe for the first four bytes. The fifth byte will overrun the allocated data and tramp on something else which will yield undefined behaviour (might crash, might not). Also, you don't null terminate the string with '\0' after you finish writing the chars, so you'll probably introduce another crash when you try and call a string routine (strcpy) on it - unless the memory after your string happened to contain zeros anyway, but naturally you shouldn't rely on this chance!
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ C_dynamic_memory_allocation
C dynamic memory allocation - Wikipedia
February 15, 2026 - If one wishes to allocate a similar array dynamically without using a variable-length array, which is not guaranteed to be supported in all C11 implementations, an array can be allocated using malloc, which returns a void pointer (indicating that it is a pointer to a region of unknown data ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 24901464 โ€บ dynamic-memory-allocation-practice
c - Dynamic Memory Allocation Practice - Stack Overflow
Now you have *string_array[0] through *string_array[9], each having a place in memory but no memory space. (big difference) 3) Allocate memory space for each char *, thus creating char arrays