문제

Concerning a pointer to pointer I wonder if its ok with the following:

    char** _charPp = new char*[10];

     for (int i = 0; i < 10; i++)
    ´   _charPp[i] = new char[100];

That is - if I want a pointer to pointer that points to 10 char-arrays.

The question - is this ok now or do I have to make some kind of initializing of every char-arrays? Then - how do I do that?

I will later on in the program fill these arrays with certain chars but i suspect that the arrays should be initialized with values before such as "0"

도움이 되었습니까?

해결책

Yes, it looks pretty much suitable,

int arraySizeX = 100;
int arraySizeY = 100;
char** array2d = new char*[arraySizeX] // you've just allocated memory that
                                       // holds 100 * 4 (average) bytes
for(int i = 0; i < arraySizeX; ++i)
{
    array2d[i] = new char[arraySizeY] // you've just allocated a chunk that 
                                       //holds 100 char values. It is 100 * 1 (average) bytes
    memset(array2d[i], 0, arraySizeY) // to make every element NULL
}

I will later on in the program fill these arrays with certain chars but i suspect that the arrays should be initialized with values before such as "0"

No, there's no "default value" in C++. You need to assign 0 to the pointer to make it null, or use memset() to do it with arrays.

다른 팁

Netherwire's answer shows correctly how to initialize the chars to 0. I'll address the first part of your question.

There is no requirement to initialize them yet. As long as you initialize the chars before they're read, it's correct.

Depending on the structure of your code and how you use the arrays, it may be safer to do anyway since it can be hard to find the bug if you eventually do read some of them before initialization.

Also, remember to later delete[] the arrays that you've allocated. Or better yet, consider using std::vector instead (and possibly std::string depending on what you use those arrays for.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top