Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading