Linked Questions

Popular Questions

I am trying to swap 2 elements in an array of pointers, and these pointers point to strings of different length. Another function handled allocating memory to the array and the strings, the swap function will simple take an char** array and swap the elements I need to swap. What I am wondering is when I swap the pointers, is the allocated memory for each string retained when I swap or does this get messed up?

This isn't my exact code from my project, but what it's doing is identical:

int main() {

    char** array = malloc(10 * sizeof(char*));
    char* a = (char*)malloc(4*sizeof(char*));
    char* b = (char*)malloc(14*sizeof(char*));

    a = "test";
    b = "this is a test";

    array[0] = a;
    array[1] = b;

    char*temp;
    temp = array[0];
    array[0] = array[1];
    array[1] = temp;


    free[array];
    free[a];
    free[b];

    return 0;

}

Too summarize, my question is in regard to the allocated memory of a and b. Is that allocated memory still correct/fine after the swap?

Related Questions