Search code examples
cinitializationundefined-behaviorswapdereference

Segmentation error when swapping 2D array elements with pointers


I am trying to swap 2 values in a matrix - the value in the 1st row, 2nd column (5) and the value in the 4th row, 3rd column (2).

Once compiled, the program terminates due to a segmentation error when I try to assign the value of *temp. I have the code attached below.

void swap(float *y)
{
    float *temp;
    *temp=*(y+1);
    *(y+1)=*(y+11);
    *(y+11)=*temp;
}

void main()
{
    float a[5][3]={{7,5,4},{2,7,4},{7,5,2},{8,4,2},{9,5,2}}, *aptr=&a[0][0];
    swap(aptr);
}

I am sorry for any glaring mistakes in my code, I am new to C and I'm trying to grasp the concept of pointers.


Solution

  • The pointer temp is uninitialized. So dereferencing the pointer results in undefined behavior.

    Instead you need to use an object of the type float.

    void swap(float *y)
    {
        float temp;
        temp=*(y+1);
        *(y+1)=*(y+11);
        *(y+11)=temp;
    }