How to get the size of a double char pointer?

Basically, I want to get the size of a double char pointer, EG char **x;
Not the elements of the individual arrays, but the actual number of elements inside the pointer.
I don't want to use vectors or Strings either, I know how to do it that way, but it looks ugly.
So if I could get some feedback on this, it would be appreciated. :-)


Answer this question

How to get the size of a double char pointer?

  • frrobi

    You're right. Something like:
    int xsize = 20;
    char** x = malloc(xsize * sizeof(char*));
    // Initialize it first
    int ix;
    for (ix = 0; ix < xsize; ++ix) x[ix] = NULL;
    // Now allocate the elements from something, say char* table[]
    for (ix = 0; ix < xsize; ++ix) {
    x[ix] = malloc((strlen(table[ix]) + 1) * sizeof(char*));
    strcpy(x[ix], table[ix]);
    }
    // Go to town...
    ...
    // Cleanup
    for (ix = 0; ix < xsize; ++ix) free(x[ix]);
    free(x);

    I haven't tried it, please excuse any typing mistakes.

    Last but not least, there are a million ways to really mess up your heap using code like this. Vectors and Strings were invented to avoid the dreaded General Protection Fault and random crashes due to heap corruption. Save yourself loads of time debugging crashing programs and hit the books instead.



  • Koolchamp

    Its not really that I need to do it, but more that I want to know how to do it to make my code more efficient. I'm the kind of guy who likes to "re-invent the wheel" just to see if i'm skilled enough to actually do it. :-) And if I can figure it out, great. I would have a better understand of c++. Thanks for the feedback.

  • Brian Pos

    Go for it man, there's no better way to figure out what is really going on. You're program will be a Porsche but you'll have to bring it back to the shop once a month for a $1000 repair. Start off by using the new and delete operators to make it really C++ instead of "C". Then start using new string[]. Then grok copy constructors and use vector<>. It's going to be a helluva ride but you'll be black-belt when you're done.


  • Rob Daigneau

    If you’re allocating on the heap then _msize() might be quite useful for getting the size in bytes.


  • tkim11

    not easy without element count

    Kuphryn


  • sherifsoft2002

    I want the array to stay dynamic, so malloc and realloc are probably what I need to be using. I think I need to initialize the master array first, then with a loop, initialize each element. How to do that though, i'm not quite sure.

  • J. Newman

    Not sure how you initialize this pointer. But if you do it like this:
    char **x = new char* [20];
    it would have 20 (not yet initialized) elements.



  • How to get the size of a double char pointer?