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);  
1

1 Answer 1

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);   
Sign up to request clarification or add additional context in comments.

2 Comments

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).
@JasonBlock You just said it: 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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.