简体   繁体   中英

Assigning pointers to pointers

I have pointer to pointers to char set as:

    char **A;
    char **B;

I am making string sorting using Radix-Sort, and i have to sort it a few times, but if I sort it, it's just sorting array A and saves the result in array B . What I want to do, is to assign A to be B , which is already almost-sorted A , but when I do:

    A = B;

I just set the pointers, right? Which means A points now at B . And, when I later reassign values I have multiple results of same string. For example:

    A = {"aa", "ba", "bc", "bd"};

After sorting and using A = B , the output looks like:

    B = {"aa", "aa", "bc", "bd"};

I also tried using memcpy() - which should copy what B points at to place that is pointed by A , correct? But result is the same. No idea how to get this to work. Wasn't sure whether to post here full code, so I uploaded it on pastebin .

Thanks for any help in advance.

Edit2: With a bit help, changed it and it works fine with memcpy() , but it still doesn't 'stable' sorts, and instead of B = {"bb", "bc"} I have the opposite: B = {"bc", "bb"} . I'm still fighting it, but with no results... yet.

void CSort(int p){

int k = 123;
int C[k];
int i;

for(i = 0; i <= k; i++){
    C[i] = 0;
}

for(i = 0; i < ILE; i++){
    C[(int)As[i][p]]++;
}

for(i = 1; i <= k; i++){
    C[i] = C[i] + C[i - 1];
}

for(i = 0; i < ILE; i++){     // ile means how many words there are
    Bs[C[(int)As[i][p]] - 1] = As[i];
    printf("As[%i][%i] == %c ", i, p, As[i][p]);
    printf("C[%i] == %i ", (int)As[i][p], C[(int)As[i][p]]-1);
    printf("  Bs[%i]  == %s \n", C[(int)As[i][p]] - 1, Bs[C[(int)As[i][p]] - 1]);

    //(As[i], Bs[C[(int)As[i][p]]], sizeof(As[i]));
    C[(int)As[i][p]]--;
}


}

This is my Counting Sort, and here comes my radix:

void RSort(int d){
    int i;
    for(i = d; i >= 0; i--){
        CSort(i);
        memcpy(As, Bs, sizeof(*As) * ILE);
    }
}

I haven't even got idea - why - because on paper, it works just fine!

To fix my problem, all i had to do, was to change order in last loop:

for(i = 0; i < ILE; i++)

change to

for(i = ILE - 1; i >= 0; i--)

And everything works just fine!

When you assign

 A = B;

you assign A to point to the same memory B points at, not A to point at B .

In order to copy the array you would need to allocate memory to hold it and memcpy all contents from B to A

char ** A = malloc(sizeof(*A) * numitems);
memcpy(A, B, sizeof(*A) * numitems);

Then if you sort A or B it will not affect the other because you have copies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM