#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2003
    Posts
    10
    Rep Power
    0

    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. #2
  3. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    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];
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2003
    Posts
    10
    Rep Power
    0
    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!
  6. #4
  7. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,648
    Rep Power
    4248
  8. #5
  9. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2003
    Posts
    18
    Rep Power
    0
    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.

IMN logo majestic logo threadwatch logo seochat tools logo