srdja / Collections-C

A library of generic data structures for the C language.
http://srdja.github.io/Collections-C
GNU Lesser General Public License v3.0
2.82k stars 328 forks source link

cc_array_reverse() fails when element count is even #153

Closed 766F6964 closed 1 year ago

766F6964 commented 2 years ago

Summary: The array reverse function fails to correctly reverse the elements. Look at the following example:

// ...
struct cc_array *arr;
cc_array_new(&arr);

int v0 = 0, v1 = 1, v2 = 2, v3 = 3;
cc_array_add(arr, &v0);
cc_array_add(arr, &v1);
cc_array_add(arr, &v2);
cc_array_add(arr, &v3);

cc_array_reverse(arr);

for (size_t i = 0; i < arr->size; ++i) {
    int *elem;
    cc_array_get_at(arr, i, (void *) &elem);
    printf("i=%zu arr[%zu]=%d\n", i, i, *elem);
}
// ...

The expected output should be:

i=0 arr[0]=3
i=1 arr[1]=2
i=2 arr[2]=1
i=3 arr[3]=0

However, instead this is the result:

i=0 arr[0]=3
i=1 arr[1]=1
i=2 arr[2]=2
i=3 arr[3]=0

Cause: It seems the problem is in cc_array.c, line 690, when the list has an even amount of elements. Changing it to this: for (size_t i = 0, j = ar->size - 1; i < j; i++, j--) fixes the problem.

srdja commented 1 year ago

Solved by https://github.com/srdja/Collections-C/pull/156