|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Dynamic Arrays with undeclared size
from a friend:
i wanna declare a string array, however, i dunno the size of the array before the call the main, sth like this: int num; char *names[]; // this line looks wrong, but i dunno how else to put it .... int main() { .... num = some_number // num gets assigned; names = new char[num][256]; .... } 256 can be the max length of the strings in the array, if allocating that memory at the beginning is of any use i didn't tho, b/c i'm thinking, array of strings is actually a pointer to an array of chars, so it'd look like char[][256], but the compiler's gonna complain about that... i've tried various combinations of char[][], *char[], etc etc... these generate conversion errors... the whole problem stems from the fact that i must dynamically assign the size (i.e. dunno the size of the array before getting to main) thx!! i also dont mind if someone'd tell me how to assign strings into the array after successfully declaring the array also, just in case. |
|
#2
|
||||
|
||||
|
you were close. you just need to remove the last brackets in this line: names = new char[num][256];
so it looks like this: names = new char[num]; that will create an array of maxSize num. edit: the new function returns a pointer to the allocated memory. so names must be a pointer to a character: char *names = new char[num]; |
|
#3
|
|||
|
|||
|
Ah...i c...I'll test it out later tonight....
thanks... p.s. additional replys or rebuttals will be good too...it's nice to learn different solutions and other ppl's views... thanks! |
|
#4
|
||||
|
||||
|
|
|
#5
|
|||
|
|||
|
Remember,
Code:
char **names = (char**) new char*[num]; only declares a array of pointer to string objects. You have to alloc memory for every string, too. Code:
for(int i=0; i<num; i++) {
names[i] = (char*) new char[256];
}
Do not forget to free the memory you've assigned. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Dynamic Arrays with undeclared size |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|