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
🌐
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.
🌐
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 › 121695-creating-using-dynamic-array-c-strings.html
Creating and Using a dynamic array of C strings?
The size of the word is guaranteed to be less than 100, so I've allocated memory to be a little above 100 for each word. The code seems to work find, but... it keeps crashing whenever I try to retrieve a string. Any help? ... /*Some standard headers that have been omitted*/ #define STRING_MAX 102 #define FALSE 0 #define TRUE 1 #define ARTICLE 0 #define NOUN 1 #define VERB 2 #define PREPOSITION 3 char **preps; char **nouns; char **verbs; char **arts; int numWords[4]; void allocateWords(char ** words, int type) { int size_x = numWords[type]; int size_y = STRING_MAX; int i=0; if ( (words = (char
🌐
Quora
quora.com › In-C-programming-how-do-you-create-a-dynamic-string-array-and-perform-string-operations-with-elements-of-the-array-and-a-constant-string
In C programming, how do you create a dynamic string array and perform string operations with elements of the array and a constant string? - Quora
Answer (1 of 2): In C a string is simply an array of characters (char) with a NULCHAR ([code ]'\0'[/code]) as the last character. That is all it is. C string functions all key off this NULCHAR at the end, for their operations, and each function ...
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.

🌐
Stack Overflow
stackoverflow.com › questions › 44059939 › c-dynamic-array-of-strings
C dynamic array of strings - Stack Overflow
I'm trying to write a simple implementation of dynamic arrays of strings in C. Here's my code (minus the includes and main function etc ...): typedef char* string; typedef struct { string* l...
Find elsewhere
🌐
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
The pointer array “str_array[i]” is used to point and store strings in the array. Lastly, the “for” loop is used to iterate the array. After that, we printed the array using the “printf” function. ... It can be observed that we have successfully created a dynamic array of strings using the “malloc()” function.
🌐
Quora
quora.com › How-do-I-create-an-array-of-strings-in-c++-dynamically-using-pointers
How to create an array of strings in c++ dynamically using pointers - Quora
Answer (1 of 9): Just like you create an dynamic array of int type, you can also create an array of string which is nothing but of type const char* type in C/C++. As like we make an array of int, we create a pointer of int* type, so for string which is const char* type, we make pointer of const ...
🌐
Stack Overflow
stackoverflow.com › questions › 51181037
How to manage a dynamic array of strings in C - Stack Overflow
Visit chat · 1 Dynamic Allocation of an Array of Strings in C · 0 Reading and storing dynamically to char array · 1 Segmentation fault while trying to make a dynamically allocated array of strings in C · 0 Trouble dynamically allocating memory for string array ·
🌐
GeeksforGeeks
geeksforgeeks.org › c language › dynamic-array-in-c
Dynamic Array in C - GeeksforGeeks
July 23, 2025 - Array in C is static in nature, so its size should be known at compile time and we can't change the size of the array after its declaration. Due to this, we may encounter situations where our array doesn't have enough space left for required elements or we allotted more than the required memory leading to memory wastage. To solve this problem, dynamic arrays come into the picture.
🌐
Stack Overflow
stackoverflow.com › questions › 22973860 › dynamic-array-of-strings-in-c
Dynamic array of strings in C - Stack Overflow
char **names; names = malloc(sizeof(char *)); files = fileslog_get(FLOG_STATE_NEWOUT, -1); i = 0; while(files[i].file_id != NULL) { if(stat(files[i].file_id, &st) > 0 && st.st_size < 64100) { if(i != 0) names = realloc(names, (i+1)*sizeof(char *)); names[i] = malloc(256); strcpy(names[i], files[i].file_id); } ++i; } tot_files = i; A valid version would also be having a dynamic array of strings of size 256, but I could not even compile it (using char *names[256] and deleting the malloc(256) it did not even compile).
🌐
Sololearn
sololearn.com › en › Discuss › 3037708 › im-confused-on-how-to-add-strings-to-a-dynamically-array-in-c
I’m confused on how to add strings to a dynamically array in c | Sololearn: Learn to code for FREE!
I’m confused on that part. The hint that I got from the assignment is the following” This is one way to add things to a dynamically allocated array. Every time we add s
Top answer
1 of 1
1

The link in the comments above [mostly] assumes that we know the number of elements before we allocate the array.

Thus, it's not as useful when we can only get the number of elements by reading the input file. For TTY input from stdin this won't work too well because we can't rewind the file.

A dynamic array is generally useful. So, I've created one that allows arbitrarily sized array elements. And, it can grow/expand as we add new elements.

And, for demo purposes here, I've created a "book" structure that stores Author's name and book title.

Here is the code. It is annotated:

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

// general dynamic array control
typedef struct {
    void *arr_base;                         // pointer to data
    size_t arr_size;                        // bytes / element
    size_t arr_count;                       // number of elements in use
    size_t arr_capacity;                    // number of elements allocated
} arr_t;

// book control
typedef struct {
    char *book_last;                        // author's last name
    char *book_first;                       // author's first name
    char *book_title;                       // book title
} book_t;

// arrnew -- allocate new array
arr_t *
arrnew(size_t siz)
{
    arr_t *arr = calloc(1,sizeof(*arr));

    // store the number of bytes in each element
    arr->arr_size = siz;

    return arr;
}

// arrappend -- get new element in array
// RETURNS: pointer to element
void *
arrappend(arr_t *arr)
{
    size_t index;
    void *ptr;

    // get index of element to store into and increase the in use count
    index = arr->arr_count++;

    do {
        // we have enough space for the new element already
        if (arr->arr_count < arr->arr_capacity)
            break;

        // increase allocated amount
        // NOTE: the increment is arbitrary
        arr->arr_capacity += 10;

        // grow the array
        arr->arr_base = realloc(arr->arr_base,
            arr->arr_capacity * arr->arr_size);

        // got the larger array
        if (arr->arr_base != NULL)
            break;

        perror("arrappend");
        exit(1);
    } while (0);

    // point to element we can store into
    ptr = arr->arr_base;
    ptr += index * arr->arr_size;

    return ptr;
}

// arrtrim -- trim array to number of elements actually used
void
arrtrim(arr_t *arr)
{

    arr->arr_capacity = arr->arr_count;
    arr->arr_base = realloc(arr->arr_base,arr->arr_capacity * arr->arr_size);

    if (arr->arr_base == NULL) {
        perror("arrtrim");
        exit(1);
    }
}

// arrfree -- free up array storage
void
arrfree(arr_t *arr)
{

    free(arr->arr_base);
    free(arr);
}

int
main(void)
{
    char buf[300];
    char *cp;
    book_t *book;

    // echo line if input is _not_ a tty [mostly for demo]
    struct termios tio;
    int echo = tcgetattr(fileno(stdin),&tio) < 0;

    // get new array
    arr_t *arr = arrnew(sizeof(book_t));

    printf("Gimme Books's Titles:\n");

    while (1) {
        // get next line -- stop on EOF
        char *cp = fgets(buf,sizeof(buf),stdin);
        if (cp == NULL)
            break;

        // echo line if input is _not_ a tty
        if (echo)
            fputs(buf,stdout);

        // strip newline
        buf[strcspn(buf,"\n")] = 0;

        // stop on blank line
        if (buf[0] == 0)
            break;

        // get new book struct
        book = arrappend(arr);

        // get author's last name
        char *tok = strtok(buf," \t");
        book->book_last = strdup(tok);

        // get author's first name
        tok = strtok(NULL," \t");
        book->book_first = strdup(tok);

        // get the book title
        tok += strlen(tok);
        ++tok;
        for (;  *tok != 0;  ++tok) {
            if (*tok != ' ')
                break;
        }
        book->book_title = strdup(tok);
    }

    arrtrim(arr);

    // show all the books
    book = arr->arr_base;
    for (size_t idx = 0;  idx < arr->arr_count;  ++idx, ++book)
        printf("Last: %s First: %s Title: %s\n",
            book->book_last,book->book_first,book->book_title);

    // release storage for each book
    book = arr->arr_base;
    for (size_t idx = 0;  idx < arr->arr_count;  ++idx, ++book) {
        free(book->book_last);
        free(book->book_first);
        free(book->book_title);
    }

    // release array storage
    arrfree(arr);

    return 0;
}

Here is the program input:

Lambstewer Abel A Tale of Two Cities
Smith John      A baker's tale
Jones Fred      Never On Sunday

Here is the program output:

Gimme Books's Titles:
Lambstewer Abel A Tale of Two Cities
Smith John      A baker's tale
Jones Fred      Never On Sunday
Last: Lambstewer First: Abel Title: A Tale of Two Cities
Last: Smith First: John Title: A baker's tale
Last: Jones First: Fred Title: Never On Sunday
🌐
Diveintosystems
diveintosystems.org › book › C2-C_depth › strings.html
2.6.1. C's Support for Statically Allocated Strings (Arrays ...
In the previous chapter we introduced arrays and strings in C. In this chapter we discuss dynamically allocated C strings and their use with the C string library. We first give a brief overview of statically declared strings.
🌐
Physics Forums
physicsforums.com › other sciences › programming and computer science
How to dynamically allocate an array of strings • Physics Forums
May 10, 2017 - There are recommendations to use realloc to expand the array as needed and to avoid freeing the input strings until after they have been printed. Some participants propose using a struct to hold the conversation pairs instead of a flat array, citing potential benefits in organization. Concerns are raised about the implications of using const with pointers, with discussions on how it affects memory management and modification rights. One participant questions when to free the dynamically allocated strings, leading to clarification that they should be freed after printing.
🌐
Reddit
reddit.com › r/c_programming › dynamically allocated array of strings?
r/C_Programming on Reddit: Dynamically Allocated Array of strings?
June 8, 2017 -

I need a little help with a problem. Just a little guidance in the logic behind solving a problem.

I have to create a program that keeps asking for a string input, and storing it in an array, until a user inputs the string "quit". The only thing I can assume, is that the string will be no longer than 100 chars, but there is no limit on how many strings a user might input.

I think I would have do to this in a while loop to keep asking for an input, and then use strcmp() to see when a person enters "quit" in order to break the loop.

My problem is, I'm not too sure how to dynamically allocate an array.

Top answer
1 of 3
1

You can allocate an array of arbitrary length with malloc() (it's like "new" in Java), and make it grow or shrink with realloc().

You have to remember to free the memory with free() as in C there is not garbarage collector.

Check: http://www.gnu.org/software/libc/manual/html_node/Memory-Allocation.html#Memory-Allocation

Edit:

#include <stdlib.h>
#include <string.h>
int main(){
    char * string;
    // Lets say we have a initial string of 8 chars
    string = malloc(sizeof(char) * 9); // Nine because we need 8 chars plus one \0 to terminate the string
    strcpy(string, "12345678");

    // Now we need to expand the string to 10 chars (plus one for \0)
    string = realloc(string, sizeof(char) * 11);
    // you can check if string is different of NULL...

    // Now we append some chars
    strcat(string, "90");

    // ...

    // at some point you need to free the memory if you don't want a memory leak
    free(string);

    // ...
    return 0;
}

Edit 2: This is the sample for allocate and expand an array of pointers to chars (an array of strings)

#include <stdlib.h>
int main(){
    // Array of strings
    char ** messages;
    char * pointer_to_string_0 = "Hello";
    char * pointer_to_string_1 = "World";
    unsigned size = 0;

    // Initial size one
    messages = malloc(sizeof(char *)); // Note I allocate space for 1 pointer to char
    size = 1;

    // ...
    messages[0] = pointer_to_string_0;


    // We expand to contain 2 strings (2 pointers really)
    size++;
    messages = realloc(messages, sizeof(char *) * size);
    messages[1] = pointer_to_string_1;

    // ...
    free(messages);

    // ...
    return 0;
}
2 of 3
0

Consider creating apropriate types suitable for you problem. For example, you can create a struct holding a pointer and sn integer length to represent the dynamic arrays.