气泡排序方法的小问题

时间:2018-11-15 14:55:24

标签: c malloc

我的Visual Studio总是抛出不同的异常(气泡sort.exe触发了断点。) 有时在第6行:(arr_2 =(int *)malloc(size); 有时在空闲(arr)和free(arr_2);

的行上
int bubble(int size, int * arr) {
for (int i = 0; i < size; i++) {
    printf("array[%d] = %d \n", i, arr[i]);
}
int * arr_2;
arr_2 = (int *)malloc(size);

for (int i = 0; i < size; i++) {
    arr_2[i] = arr[i];
}
for (int i = 0; i < size; i++) {
    printf("2array_2[%d] = %d \n", i, arr_2[i]);
}
int numb;
for (int i = 0; i < size; i++) {                                               
    if (arr[i] > arr[i + 1]) {
        numb = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = numb;
    }

}
free(arr_2);
return 0;
};
int main(){
char size[100];
printf("Hello! Please enter the size of the array that will be sorted with 
bubble sort method \n Maximum size is 100 \n");
gets_s(size);
int size_1 = atoi(size);
int * arr;
arr = (int *)malloc(size_1);
for (int i = 0; i < size_1; i++) {
    arr[i] = rand();
}
bubble(size_1, arr);


free(arr);
return 0;
}

2 个答案:

答案 0 :(得分:0)

使用类似这样的内容:

int bubble(int size, int * arr)
{
    int numb;
    for(int i = 0; i < size - 1; i++)
        for(int j = 0;j < size - i - 1; j++)
            if(arr[j] > arr[j + 1])
            {
                numb = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = numb;
            }

    return 0;
};


// using
int main()
{
    char size[100];
    printf("Hello! Please enter the size of the array that will be sorted with bubble sort method \n Maximum size is 100 \n");
    gets_s(size);
    int size_1 = atoi(size);

    int * arr = new int[size_1];

    for(int i = 0; i < size_1; i++)
        arr[i] = rand();
    bubble(size_1, arr);
    delete []arr;
}

您不需要输入数组的副本。

答案 1 :(得分:0)

使用malloc保留内存时,应转换为以字节为单位的大小。 使用malloc(number_of_elements * sizeof(element))。

int size_1 = atoi(size);
int * arr;
arr = (int *)malloc(size_1 * sizeof( int ) );
for (int i = 0; i < size_1; i++) {
    arr[i] = rand();
}