You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **orderedIds;

orderedIds = malloc(variableNumberOfElements * sizeof(char*));
for (int i = 0; i < variableNumberOfElements; i++)
    orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...

Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"

Answer from MByD on Stack Overflow
🌐
Linux Hint
linuxhint.com › create-array-strings-using-malloc-c-programming
How to Create an Array of Strings Using Malloc() in C Programming – Linux Hint
To create an array of strings using the “malloc()” C standard function, first create a simple C program and declare two arrays, one of which is a pointer array. After that, utilize the “malloc()” function by using the “pointer-array = (cast-type*) malloc(input-array*size of char)” ...
🌐
USNA
usna.edu › Users › cs › adina › teaching › ic210 › fall2021 › lec › l38 › lec.html
Arrays and strings in C
Once you've allocated space for some chars, your pointer can be used with scanf to read in strings from the user: ... char* aString = malloc( 20*sizeof(char) ); scanf("%s",aString); // free(aString) later Finally, the above is all about creating and reading strings.
🌐
Quora
quora.com › How-do-you-allocate-memory-using-malloc-with-an-array-of-strings-as-its-argument-in-the-C-programming-language
How to allocate memory using malloc() with an array of strings as its argument in the C programming language - Quora
Answer (1 of 2): That’s not how the malloc function works. The malloc function allocates a contiguous block of memory, whose size is the specified number of bytes. The argument to malloc is the requested number of bytes.
🌐
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 - For each pointer in the array, allocate memory for the string using the malloc function. Use the sprintf function to assign value to the string in the array. Free memory for each string using the free function.
🌐
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

🌐
Cprogramming
cboard.cprogramming.com › c-programming › 62010-how-use-malloc-array-strings.html
how to use malloc for array of strings
Hi all, how do i use malloc to allocate memory for an array of strings? can i write the code like this? Code: char *line = (char *)malloc(sizeof(char)
Top answer
1 of 2
8

You know from the start you will have number strings to store so you will need an array of size number to store a pointer to each string.

You can use malloc to dynamically allocate enough memory for number char pointers:

char** strings = malloc(number * sizeof(char*));

Now you can loop number times and allocate each string dynamically:

for (int i = 0; i < number; i++) {
   // Get length of string
   printf("Enter the length of string %d: ", i);
   int length = 0;
   scanf("%d", &length);

   // Clear stdin for next input
   int c = getchar(); while (c != '\n' && c != EOF) c = getchar();

   // Allocate "length" characters and read in string
   printf("Please enter string %d: ", i);
   strings[i] = malloc(length * sizeof(char));
   fgets(strings[i], length, stdin);
}
2 of 2
1

Since you want to save both the length and the string, I'll suggest that you put them together in a struct. Like

struct string
{
    int length;
    char* str;
};

Now you can dynamically create an array of this struct and dynamically assign memory for the individual strings.

Something like:

#include <stdio.h>
#include <stdlib.h>

struct string
{
    int length;
    char* str;
};

int main(void) {
    int i;
    char tmp[128];
    int number = 3;
    struct string* strings = malloc(number * sizeof *strings);

    // read the input
    for (i=0; i<number; ++i)
    {
        printf("length?\n");
        if (fgets(tmp, sizeof tmp, stdin) == NULL)
        {
            printf("error 1");
            exit(1);
        }
        int length;
        if (sscanf(tmp, "%d", &length) != 1)
        {
            printf("error 2");
            exit(1);
        }
        strings[i].length = length;
        strings[i].str = calloc(length + 2, 1);
        printf("string?\n");
        if (fgets(strings[i].str, length + 2, stdin) == NULL)
        {
            printf("error 3");
            exit(1);
        }
        if (strings[i].str[length] != '\n')
        {
            printf("error 4");
            exit(1);
        }
        strings[i].str[length] = '\0';
    }

    // print the strings
    for (i=0; i<number; ++i)
    {
      printf("len=%d str=%s\n", strings[i].length, strings[i].str);
    }

    // Clean up, i.e. free the memory allocated
    for (i=0; i<number; ++i)
    {
        free(strings[i].str);
    }
    free(strings);

    return 0;
}

Note: You should also check that all malloc/calloc are succesful, i.e. doesn't return NULL. For clarity I skipped that.

Find elsewhere
🌐
Diveintosystems
diveintosystems.org › book › C2-C_depth › strings.html
2.6.1. C's Support for Statically Allocated Strings (Arrays ...
When dynamically allocating space to store a string, it’s important to remember to allocate space in the array for the terminating '\0' character at the end of the string. The following example program demonstrates static and dynamically allocated strings (note the value passed to malloc):
🌐
Reddit
reddit.com › r/learnprogramming › [c] storing strings using an array of char pointers and malloc.
r/learnprogramming on Reddit: [C] Storing strings using an array of char pointers and malloc.
July 29, 2013 -

I've been given the task of reading words into an array and then running insertion sort on them. The way it has been set out to do this is by using an array of char pointers and then assigning memory to each index in order to store a string. The code for that is already in place. But I just don't understand how using malloc makes space for a sting within a char? I'm honestly not even sure if what I just wrote makes sense. Pointers are frying my brain. Any help would be much appreciated. I've done a fair bit of Java before if that helps any explaination .

🌐
Quora
quora.com › Can-we-use-the-malloc-function-to-create-arrays-with-strings-as-elements
Can we use the malloc function to create arrays with strings as elements? - Quora
Answer (1 of 2): As strings may be different lengths I would use an array of pointers to the strings. You could safely malloc the array of size n times the size of a pointer. I would malloc the strings separately. I would also create a reusabke struct called something likeText that starts with t...
🌐
George Washington University
www2.seas.gwu.edu › ~simhaweb › C › modules › module3 › module3.html
Module 3: Pointers, strings, arrays, malloc
Strings are enclosed in double-quotes. ... Declare an array with a static size. Declare an array variable without a size, and allocate memory dynamically. ... // Note the use of the "sizeof" keyword. A2 = (int*) malloc (sizeof(int) * 10); for (i=0; i < 10; i++) { A2[i] = i * 100;
🌐
YouTube
youtube.com › portfolio courses
Dynamically Allocate Memory For An Array Of Strings | C Programming Example - YouTube
How to dynamically allocate memory for an array of strings using C. Source code: https://github.com/portfoliocourses/c-example-code/blob/main/dynamic_array_...
Published   January 21, 2022
Views   49K
🌐
Ars OpenForum
arstechnica.com › forums › operating systems & software › programmer's symposium
C - using malloc to dynamically assign memory for a array of strings | Ars OpenForum
November 2, 2008 - Use fgets() instead:<BR><pre class="ip-ubbcode-code-pre"> if (!fgets(str, sizeof str)) { /* read operation failed */ } else { /* read succeeded */ } </pre><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content"><pre class="ip-ubbcode-code-pre"> printf("\n enter price \n"); fflush(stdin); scanf("%f", &cost); break; case 2: printf("\n enter description \n"); fflush(stdin); gets(str); printf("\n enter price \n"); fflush(stdin); scanf("%f", &cost); break; case 3: printf("\n enter description \n"); fflush(stdin); gets(str); prin
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.