[Solved] Write a program that swaps values within an array [closed]


There’s several problems with your code.

First, the swap function doesn’t work. You’re swapping the values of the pointers that are local variables inside the function, you’re not swapping the array elements they point to. You need to indirect through pointers to get the values.

int temp1 = *a;
*a = *b;
*b = temp1;

And similar for all the other pairs you’re swapping.

Second, swap expects pointers as arguments, but you’re passing int variables from main(). You need to use pointer variables, which you set to the addresses of the array elements:

int *a = &arr[0], *b = &arr[7], *c = &arr[8], *d = &arr[3], *e = &arr[14];

You might consider changing the swap() function so it just takes two pointers, and call it 3 times to do all 3 swaps.

Finally, to print the array, you need to print the elements in a loop:

printf("Swapped array: ");
for (i = 0; i < 15; i++) {
    printf("%d ", arr[i]);
}
printf("\n");

4

solved Write a program that swaps values within an array [closed]