Question:
C++ Char** How can I make this works?
anonymous
2009-07-10 21:13:47 UTC
char** strDb;
strDb = new char*[SIZE];

for(int i=0; i cin.getline(strDb[i], 256);
}

The input is not work correctly, anyone know how to get it works?
Four answers:
Stephanie
2009-07-11 04:06:52 UTC
the problem is.... Think of strDb as being a list of strings. You've set the size (length) of the list, but you haven't defined the address of each each individual element. Thus, when you call getline, you're trying to write into an uninitialised area of memory, which is very bad and will make your program do strange things.



Your for loop should read something like:



#define STRLENGTH 256



for (int i = 0; i < SIZE; ++i)

{

strDb[i] = new char[STRLENGTH];

cin.getline(strDb[i], STRLENGTH];

}



Note that you will have to iterate over it and call delete[] on EACH ELEMENT of strDb, before calling delete[] strDb;, to free the memory



(the immediately above answer is almost correct also but it does not initialize the overall container so it'll segfault)
The Phlebob
2009-07-10 21:29:37 UTC
The new char*[ SIZE ] creates a pointer to an array of char consisting of SIZE elements (characters), not an array of strings or pointers to strings. This makes the getline() use an invalid address (probably, but not reliably, NULL).



Hope that helps.
anonymous
2009-07-11 02:19:28 UTC
Hm....



















U can use:

char ** mystring;

for (int i=0; i
mystring[i] = new char [256];

cin.getline(mystring[i],256);

}
anonymous
2009-07-10 21:27:44 UTC
for(int i=0; i
strDb[i] = new char[MAX_INPUT_LEN];

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...