繁体   English   中英

带有void function的bubblesort二维数组的问题

[英]The problem of bubblesort 2D array with void function

当我想对数组进行bubblesort时出现错误。 我认为问题在于指针。 错误在这里if (array[i * 3 + j] > array[i * 3 + m])错误名称: 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;
    }
}

冒泡排序bubblesort在其原型中缺少*

此外, return语句应该移到外部for语句的主体之外,并且某些索引值不正确。

这是修改后的版本:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM