Hello,
I have a problem. I need to make an array of pointers, without knowing beforehand the size of the array. Is this possible?
Code:const char* arrayOfPointers[];
Printable View
Hello,
I have a problem. I need to make an array of pointers, without knowing beforehand the size of the array. Is this possible?
Code:const char* arrayOfPointers[];
Sure:
Thing is, though, you have to remember to delete the memory. A much better way is to use an std::vector, or similar, eg:Code:int main( void )
{
const char** arrayOfPointers = 0;
// sometime later
unsigned size = 1024;
arrayOfPointers = new const char*[ size ];
// do something usefull
delete [ ] arrayOfPointers;
}
Code:#include <vector>
int main( void )
{
std::vector< const char* > arrayOfPointers;
// sometime later
unsigned size = 1024;
arrayOfPointers.resize( size );
// do something useful...memory will be deleted by vector object...
}
Thank you.
Quick question:
Can an element of an array of pointers be assigned a string, or just a single character?
if it is an array of char * ptrs sure...
How about this?
Would the output be:Code:string* str = NULL;
str = new string;
*str = "Yes, a string...\n";
*str += "Yes, another string...\n";
*str += "Yes, even another string...\n";
int sizeOfStr = str->size();
char* arrayOfPointers[] = NULL;
//several code lines later...
arrayOfPointers = new char*[sizeOfStr];
string* anotherStr = NULL;
anotherStr = new string;
void doStuff();
void doStuff() {
for (int = 0; i < sizeOfStr; i++) {
while (str->at[i] != '\n') {
*anotherStr += str->at[i];
}
*arrayOfPointers[i] = *anotherStr->data();
anotherStr = NULL; //reset this pointer
}
}
int main() {
doStuff();
int sizeOfArray = sizeof(arrayOfPointers);
for (int = 0; i < sizeOfArray; i++) {
cout<< *arrayOfPointers[i] <<endl;
}
delete str;
delete [] arrayOfPointers;
delete anotherStr;
return 0;
}
?Quote:
Yes, a string...
Yes, another string...
Yes, even another string...
Bump.
For others' benefit.
For the record, I tried it (though obviously including <string> and <iostream>), but it didn't compile. It said it expected constructor, destructor, or type conversion before the '=' token for the "string* str = NULL" line, as well as several lines after that. After changing the string pointer to a string object, it now says 'string' does not name a type, so obviously its not seeing the string class's definition for some reason, and I don't know why, seeing as I included it....
Also note that the code was only an example anyway. In the real code that I was really asking about, all variables (including the ones that are created in dynamic memory) are created inside functions.
Dude! The clumsiest "programming ninja" ever!