Home > other >  Core keeps dumping when trying to reverse array using a function to swap values of 2 pointers
Core keeps dumping when trying to reverse array using a function to swap values of 2 pointers

Time:02-23

#include<stdio.h>

int main() {
    /* read integer array */
    int n, i;
    scanf("%d", &n);
    int *a = (int *)malloc(n * sizeof(int));
    for (i = 0; i < n; i  ) {
        scanf("%d", &a[i]);
    }
    
    /* reverse the array */
    for (i = 0; i < n / 2; i  ) {
        exchange(a[i], a[n - i - 1]);
    }

    /* print the array */
    for (i = 0; i < n; i  ) {
        printf("%d ", a[i]);
    }

    /* free the memory */
    free(a);

    return;
    
}

/* write a function that takes two pointers of two intergers and then exchanges the values
in those locations */
void exchange(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

This is the code, the function exchange tries to exchange the values of the integers which these two pointers are pointing to. Keeps dumping the core.

CodePudding user response:

In this call of the function exchange

exchange(a[i], a[n - i - 1]);

the both arguments have the type int while the function expects arguments of the type int *.

You need to call the function like

exchange( a   i, a   n - i - 1);

CodePudding user response:

You need to send address values for exchange functions since arguments of it are declared as pointers. Therefore, you need to change this line

exchange(a[i], a[n - i - 1]);

to this line because as I mentioned it expects addresses.

exchange(&a[i], &a[n - i - 1]);

CodePudding user response:

A nicer way would be passing the whole array and indexes to swap.

Like this: TRY IT ONLINE

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

void exchange(int **arr, int n1, int n2);

int main() {
    /* read integer array */
    int n, i;
    scanf("%d", &n);
    int *a = (int *)malloc(n * sizeof(int));
    for (i = 0; i < n; i  ) {
        scanf("%d", &a[i]);
    }
    
    /* reverse the array */
    for (i = 0; i < n / 2; i  ) {
        exchange(&a, i, n - i - 1);
    }

    /* print the array */
    for (i = 0; i < n; i  ) {
        printf("%d ", a[i]);
    }

    /* free the memory */
    free(a);

    return 0;
    
}

/* write a function that takes two pointers of two intergers and then exchanges the values
in those locations */
void exchange(int **arr, int n1, int n2) {
    int temp = (*arr)[n1];
    (*arr)[n1] = (*arr)[n2];
    (*arr)[n2] = temp;
}
  • Related