Home > Mobile >  function wcsncpy loses elements of the string
function wcsncpy loses elements of the string

Time:03-12

i have function for sort elements of void* string. it is comb sort (sorry for comments on russian). while it sorting String become shorter and loses elements.

void *SimpleSort(void *String) {
    setlocale(LC_ALL, "");
    double factor = 1.2473309; // фактор уменьшения
    int step = wcslen((wchar_t *) String) - 1; // шаг сортировки
    //Последняя итерация цикла, когда step==1 эквивалентна одному проходу сортировки пузырьком
    while (step >= 1) {
        for (int i = 0; i   step < wcslen((wchar_t *) String); i  ) {
            if (*(wchar_t *) (String   (i)) > *(wchar_t *) (String   (i   step))) {
                void *el = malloc(sizeof(wchar_t));
                wcsncpy(el, String   i, 1);
                wcsncpy(String   i, String   i   step, 1);
                wcsncpy(String   i   step, el, 1);
                wprintf(L"%ls\n", (wchar_t *) String);
            }
        }
        step /= factor;
    }
    wprintf(L"%ls\n", (wchar_t *) String);
    return String;
}

if i input asdawd, will be this enter image description here

CodePudding user response:

String is a void *, which is typically 32-bits or 64-bits on a modern architecture. Why not pass in the "real" type?

(String 1) will advance your pointer by 32- or 64- bits, because String is void *.

You are working with wchar_t, probably a 16-bit value, so any pointer or array math is incompatible between your String variable and the other variables. What you are seeing is probably the result of alignment errors between your types, and you are hiding these alignment errors with C-casts.

Remove the dangerous casting and using the real types, instead (without compile errors), and it will start working once you have fixed the compile errors.

CodePudding user response:

it is wrong to find your length so

length = wcslen((wchar_t *) String);

you should use variable for this, and it will solve

  •  Tags:  
  • c
  • Related