0

I am trying to dynamically allocate the array frags2 of size numberOfFrags and copy over the contents of the original array to it. I have tried numerous approaches and searching and do not understand what is going wrong here. sizeof on the new array returns 0 instead of what I thought I malloc'd.

Any help would be much appreciated!

 int main(int argc, const char* argv[]) {
     char* frags[MAX_FRAG_COUNT];  
     FILE* fp = fopen(argv[1], "r");
     int numberOfFrags = ReadAllFragments(fp, frags, MAX_FRAG_COUNT);
     fclose(fp);
     char** frags2 = (char**)malloc(numberOfFrags * sizeof(char*));
     for (int i = 0; i < numberOfFrags; i++) {
         frags2[i] = frags[i];
     }
     qsort(frags2, sizeof(frags2) / sizeof(char *), sizeof(char*), cstring_cmp);  
razlebe
  • 7,134
  • 6
  • 42
  • 57
Jason Block
  • 155
  • 1
  • 3
  • 9
  • See [How to find the sizeof(a pointer pointing to an array)](http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array) – Bo Persson Jul 09 '12 at 09:27

1 Answers1

4

Sizeof on the new array returns 0 instead of what I thought I malloc'd

It's not an array, it's a pointer. In this context the operator sizeof yields the size of the pointer, not the amount you allocated.

So instead of that sizeof stuff, you can try

qsort(frags2, numberOfFrags, sizeof(char*), cstring_cmp);   
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Thanks a lot, that worked. But what I don't understand is what makes the original array, frags, any different. Calling sizeof(frags) returns 80000 (MAX_FRAG_COUNT is 20000). – Jason Block Jul 09 '12 at 09:23
  • @JasonBlock [You just said it](http://c-faq.com/aryptr/aryptr2.html): *The original **array***. `frags2` is not an array, it's a pointer to which you assign an address. Another (misleading) way to put it is that "`sizeof` works at compile-time". – cnicutar Jul 09 '12 at 09:24