1

I'm trying to write a function which reverses an array.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void * reverse(void * array, int length, size_t size) {
    void * temp = malloc(size);
    int s = 0;          // start
    int e = length - 1; // end
    const int halp = length / 2;
    for (; s < halp; s++) {
        memcpy(temp, (array + s), size);
        memcpy((array + (s * size)), (array + (e * size)), size);
        memcpy((array + (e * size)), temp, size);
        e--;
    }
    free(temp);
    return array;
}

int main(int argc, char * argv[]) {
    int array[] = {0, 1, 2, 3, 4};
    for (int i = 0; i < 5; i++) {
        printf("array[%d]: %d\n", i, array[i]);
    }
    printf("------------------------------------------\n");
    reverse(array, 5, sizeof(int));
    printf("------------------------------------------\n");
    for (int i = 0; i < 5; i++) {
        printf("array[%d]: %d\n", i, array[i]);
    }
}

Result:

array[0]: 0
array[1]: 1
array[2]: 2
array[3]: 3
array[4]: 4
------------------------------------------
------------------------------------------
array[0]: 4
array[1]: 3
array[2]: 2
array[3]: 16777216
array[4]: 0

Why the result has an unexpected value?

3
  • 3
    Shouldn't it be memcpy(temp, (array + s * size), size); in your first memcpy? I mean, that seems to be the case for all the other lines. Commented Jun 7, 2015 at 9:31
  • @Gosu Please make it as an answer so that I can accept it. Commented Jun 7, 2015 at 9:35
  • Just added it as an answer, I had to test it first just to be sure :) Commented Jun 7, 2015 at 9:37

1 Answer 1

2

Change from

memcpy(temp, (array + s), size);

to

memcpy(temp, (array + s * size), size); // Note: s * size


Tested, and it works.

Output:

array[0]: 0
array[1]: 1
array[2]: 2
array[3]: 3
array[4]: 4
------------------------------------------
------------------------------------------
array[0]: 4
array[1]: 3
array[2]: 2
array[3]: 1
array[4]: 0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.