Segmentation fault while reversing an array

Solved
cosni -  
mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   -

Hello,

I wrote this code to have a function that reverses the order of the elements of an array of integers.

#include <unistd.h> void   ft_rev_int_tab(int *tab, int size) {    int    c;    int    i;    i = 0;    while (i < size / 2)    {       c = tab[i];       i = tab[size - 1 - i];       tab[size - 1 - i] = c;       i++;    } } int main() {    int    p;    int    s;    p = 5;    s = 3;    ft_rev_int_tab(&p,s);    write (1, &p, 1);    return 0; }

Yet, I get this error message and I understand what I need to do to solve this problem:

 - [1] + 5608 suspended cat - [1] 5252 segmentation fault ./a.out

Can you help me please? Thank you!

3 answers

  1. Anonymous user
     

    Hello
    For your next messages, please use syntax highlighting as described here

    For your problem, your function expects an array of int. You are not providing it


    When I was little, the Dead Sea was just sick.
    George Burns

    1
  2. PierrotLeFou
     

    This is not the only problem. Your way of swapping two values is not correct. The variable i has a double use ...

    0
  3. mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   7 943
     

    Hello,

    As Pierrot rightly pointed out in his message #2, your variable i has a dual role:

    • sometimes one of the two indices where the swap occurs,
    • sometimes a value from the array (which in general is outside the valid index range of the array, and thus leads to a segmentation fault).

    Furthermore, your way of declaring your array is a bit convoluted.

    To solve all these issues, you could take inspiration from this link.

    Good luck

    0