Originally Posted by
tabstop
arrayofPointers was char**, n'est ce pas? I don't feel like going back up to find your code.
Yes, it is.
The following does what I expect:
Code:
#include <iostream>
#include <cstring>
int main() {
char **arrayofPointers;
arrayofPointers = new char*[10];
for (int i = 0; i < 10; ++i) {
arrayofPointers[i] = new char[15];
strcpy(arrayofPointers[i], "Hello world!");
}
for (int i = 0; i < 10; ++i) {
std::cout << arrayofPointers[i] << std::endl;
}
return 0;
}
I'll leave it to you to compare and contrast. (We'll ignore the lack of delete[]s for the moment.)
Do I really have to point every individual element of the array of pointers to a "new" allocation in dynamic memory? I thought the "arrayOfPointers = new char*[10]" part takes care of all elements. And anyway, seeing as I'm assigning (i.e. pointing) each element of the pointer of arrays to an already existing string, I would think I wouldn't have to do that.
Code:
#include <iostream>
#include <string>
using namespace std;
struct stringStruct {
stringStruct() : arrayOfPointers(NULL) { initialize(); }
void initialize();
string* str;
string* anotherStr;
const char** arrayOfPointers;
};
void stringStruct::initialize() {
str = NULL;
anotherStr = NULL;
}
void doStuff();
int main() {
doStuff();
cin.get();
return 0;
}
void doStuff() {
stringStruct object;
object.str = new string;
*object.str = "Yes, a string...\n";
*object.str += "Yes, another string...\n";
*object.str += "Yes, even another string...\n";
int sizeOfStr = object.str->size();
object.anotherStr = new string;
int sizeOfArrayOfPointers = 0;
for (int i = 0; i < sizeOfStr; i++) {
char currentChar = object.str->at(i);
if (currentChar != '\n') {
sizeOfArrayOfPointers++; //increment this
}
}
object.arrayOfPointers = new const char*[sizeOfArrayOfPointers];
int i2 = 0;
for (int i = 0; i < sizeOfStr; i++) {
while (object.str->at(i2) != '\n') {
object.anotherStr += object.str->at(i2);
i2++;
}
object.arrayOfPointers[i] = object.anotherStr->data();
object.anotherStr = NULL; //reset this pointer
}
int sizeOfArray = sizeof(object.arrayOfPointers);
for (int i = 0; i < sizeOfArray; i++) {
cout<< object.arrayOfPointers[i] <<endl;
}
delete object.str;
delete [] object.arrayOfPointers;
delete object.anotherStr;
}