Search code examples
csegmentation-faultbubble-sort

segmentation fault: while bubble sort of arrays


#include <stdio.h>

int main(void)
{
    int i, j, tmp;
    int data[] = {1, 6, 7, 10, 9, 8};
    for ( i = 0; i < sizeof(data); i++)
        for ( j = 0; j < sizeof(data) - 1; j++)
            if (data[j] > data[j + 1])
            {
                tmp = data[j];
                data[j] = data[j + 1];
                data[j + 1] = tmp;
            }
    for (i = 0; i < sizeof(data); i++) {
        printf("%d ", data[i]);
    }
    return 0;
}

This code prints segmentation fault when run,can someone please help me to find out what is wrong


Solution

  • Change

    sizeof(data)
    

    In the condition of all the for loops to

    sizeof(data)/sizeof(data[0])
    

    This is done because sizeof(int-array) is the number of elements in the array multiplied with the sizeof(int)(which is usually 4 bytes). sizeof(data[0]) is the same as sizeof(int) as data[0] is an int. So, you can also use

    sizeof(data)/sizeof(int)
    

    In the condition of the loop.