Search code examples
c++carraysdynamic-arrayscharacter-arrays

Passing 2-D array with dynamic size between functions in C/++


This is "popular" question so I already checked the similar threads but still didnt resolve my issue.

How can I declare 2-D array to hold "strings" - I need array of array of chars AFAIK - and use it as argument to 5 functions one after another where I can pass it by reference and update the content dynamically so following function can compare it. (I might get 10 "strings" or even empty array, so I want to do it correctly with dynamic array coz array content is different from system to system).

"string" => C style string aka array of chars. MAXLEN < 32;

C solution would be more disirable but if vectors can work, why not.


Solution

  • One possible solution in C is as follows:

    char **p_strings = calloc(num_strings, sizeof(*p_strings));
    
    for (i = 0; i < num_strings; i++)
    {
        // Allocate storage for the i-th string (always leave room for '\0')
        p_strings[i] = calloc(len_string[i]+1, sizeof(*p_strings[i]));
    }
    
    
    ...
    
    // Call a function
    my_function(p_strings, num_strings);
    

    You will need to remember to free all this data when you're done with it.

    If you need to alter the length of a string, or change the number of strings, you will have to do some fairly painful reallocation. So if you're working in C++, you should probably just be using a std::vector<std::string>.

    std::vector<std::string> strings;
    
    strings.push_back("Foo");
    strings.push_back("Bar");
    
    ...
    
    my_function(strings);
    

    You can even get const pointers to C-style strings for each element, using c_str().