I’m trying to write a function that shifts all the elements in an array of strings up by one.
void shift_frags(char **frags, int frag_len, int cur) { int i; for(i = cur; i < frag_len-1; i++) { if(strlen(frags[i+1]) > strlen(frags[i])) frags[i] = realloc(frags[i], strlen(frags[i+1])*sizeof(char)); strcpy(frags[i], frags[i+1]); } free(frags[frag_len-1]); }
This is giving me the error: ‘realloc(): invalid next size: …’ Each array is dynamically allocated to be the size of a string read from a file. Shouldn’t I be able to dynamically allocate new array sizes since my frags parameter is an array of pointers?
Thanks
Since as you say the array is just an array of pointers, you do not need to perform any reallocations. You just need to copy the pointers themselves. A simple call to memmove or something similar in the portion of the array is all that is required.
Something approximating this.