0

I have an array of strings defined like this:

char** arrNames;

Now I want to dynamically allocate a size to it. I have a function that receives the new size and the array above. It goes like this:

char** AddName(char** arrNames, int nNameCount)
{
    char** arrTemp;

    arrTemp = new char[nNameCount];
    ...
    // And later I change the pointer of arrNames to arrTemp
}

Now this obviously doesn't work. So what should I be doing instead?

Thanks in advance.

3
  • 3
    Are you using C or C++? new char... will work only with C++. With C use malloc instead. Commented Apr 25, 2011 at 11:56
  • I'm using a C++ compiler (that's how they teach us), so it should work Commented Apr 25, 2011 at 11:58
  • 2
    if you want to learn C, don't use new even if you happen to be (very unwisely IMO) using a C++ compiler to compile your C code. If you want to learn C++ then in real life don't use new for this either, use a vector. For the purposes of understanding how memory allocation works in C++ you could use new for this, but if you're supposed to be learning malloc/free for use in C, then you won't do so by using C++ new[]/delete[] instead ;-) Commented Apr 25, 2011 at 12:31

4 Answers 4

5

If you want nNameCount strings, you need to allocate an array of arrays of chars (i.e an array of strings):

char** AddName(char** arrNames, int nNameCount)
{
    char** arrTemp = new char *[nNameCount];

    for (int i = 0; i < nNameCount; ++i) arrTemp[i] = new char[STRING_SIZE];
    ...
}

After this you can access each string with arrTemp[index]. Note that you still need to initialize each string.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is an working example of how to initialize Dynamic Array of Dynamic strings.

twoDStr = new char*[10];
twoDStr[0] = new char[10];

cin>>twoDStr[0];
cout<<twoDStr[0]<<endl;

Comments

0

// And later I change the pointer of arrNames to arrTemp

For this to work properly, you'd need arrNames to be a pointer to an array.

char** AddName(char*** arrNames, int nNameCount) {
    //...
    *arrNames = arrTemp;
}

Don't forget to free any previously allocated memory arrNames might refer to!

Comments

0

In C, functions for dynamically allocating memory are malloc(), calloc(), realloc() and free().

man malloc should give you more informations.

1 Comment

Gah, valloc is a legacy Posix thing, not standard C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.