MLHYLMZ
MLHYLMZ

Reputation: 33

The problem of bubblesort 2D array with void function

I get an error when I want to bubblesort an array. I think the trouble is in the pointers. The error is here if (array[i * 3 + j] > array[i * 3 + m]) Error Name: subscripted value is neither array nor pointer nor vector.

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

int *create_matrix_fill_random(int satir, int sutun);
int *bubblesort(int array);

int main() {
    srand(time(NULL));
    printf("Matrix automatically created 3x3");
    int a = 3;
    int *matrix = create_matrix_fill_random(a, a);
    matrix = bubblesort(matrix);

    return 0;
}

int *create_matrix_fill_random(int row, int col) {
    int *ptr;
    ptr = malloc(row * col * sizeof(int));
    int i, j;
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            ptr[i * col + j] = rand() % 40000 + 5;
        }
    }
    return ptr;
}

int *bubblesort(int array) {
    int m, a = 3;
    int temp;
    for (int i = 0; i < 3; i++) { 
        for (int j = 0; j < 3; j++) { 
            for (m = 0; m < 3 - 1; m++) {   
                if (array[i * 3 + j] > array[i * 3 + m]) {  
        //Mistake ^ ^ ^ ^ ^ ^ ^ ^
                    temp = array[i * 3 + j];           
                    array[i * 3 + j] = *array[i * 3 + m];
                    array[i * 3 + j] = temp;   
                }
            }
        }
        return array;
    }
}

Upvotes: 1

Views: 52

Answers (1)

chqrlie
chqrlie

Reputation: 144715

The bubblesort function has a missing * in its prototype.

Furthermore, the return statement should be moved outside the body of the outer for statement, and some of the index values are incorrect.

Here is a modified version:

int *bubblesort(int *array) {      // fix
    int m, a = 3;
    int temp;
    for (int i = 0; i < a; i++) { 
        for (int j = 0; j < a; j++) { 
            for (m = j + 1; m < a; m++) {    // fix
                if (array[i * a + j] > array[i * a + m]) {  
                    temp = array[i * a + j];           
                    array[i * a + j] = *array[i * a + m];
                    array[i * a + m] = temp;   // fix
                }
            }
        }
    }
    return array;
}

Upvotes: 1

Related Questions