Question

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);  
Was it helpful?

Solution

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);   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top