开发者

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

开发者 https://www.devze.com 2023-03-30 22:32 出处:网络
This is \"popular\" question so I already checked the similar threads but still didnt resolv开发者_运维百科e my issue.

This is "popular" question so I already checked the similar threads but still didnt resolv开发者_运维百科e 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.


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().


Assuming C++; for this I see no problem with using a vector to string (the string serves as the second dimension):

void foo(vector<string> v) {
    cout << v[0]; // Assuming the elements exist!
}

int main(int argc, char *argv[])
{
    vector<string> vString; // Make the vector

    vString.push_back("something"); // Add a string

    foo(vString); // Print out 'something'
}

In your edit you also described that the only thing that will change would be the actual string, so instead of push_backing your strings when they are needed, you can init the vector with the length:

vector<string> vString(10); // Assuming a size of 10

and then use them normally:

vString[4] = "something";

and (in response to the comment), to resize at runtime:

vString.resize(15); // Make it bigger, generates new blank strings
0

精彩评论

暂无评论...
验证码 换一张
取 消