【发布时间】:2020-09-09 19:36:05
【问题描述】:
我创建了一个从用户 N 元素获取的 (int *) 表,然后在我创建的交换和排序函数的帮助下打印出排序表。代码如下:
#include <stdio.h>
#include <stdlib.h>
void swap(int **p_a, int **p_b);
void sort(int **table, int N);
int main(void){
// Here your code !
int *table;
int elements, i;
printf("Input the number of elements to store in the array : ");
scanf("%d", &elements);
table = (int *)malloc(elements * sizeof(int));
if (table == NULL)
{
printf("Unable to allocate memory...");
return -1;
}
printf("Input %d number of elements in the array : \n", elements);
for (i=0; i<elements; i++)
{
printf("element - %d: ", i+1);
scanf("%d", (table + i));
}
printf("\nThe elements in the array before sorting: \n");
for (i=0; i<elements; i++)
printf("element - %d : %d\n", i+1, *(table + i));
sort(&table, elements);
printf("\nThe elements in the array after sorting: \n");
for (i=0; i<elements; i++)
printf("element - %d : %d\n", i+1, table[i]);
free(table);
}
void swap(int **p_a, int **p_b)
{
int temp;
temp = **p_a;
**p_a = **p_b;
**p_b = temp;
}
void sort(int **table, int N)
{
int i,j;
int current_position;
for (i=0; i<N; i++)
{
current_position = i; // current_position is the current element of the table
for (j=i; j<N; j++)
{
/*
compares all the elements after the current position
if the condition is true then the current position now is the next position, and compares it again.
When the outer loop will loop again it means that the smallest element was found and then compares the other ones
*/
if (*table[j] < *table[current_position]);
current_position = j;
}
swap(&table[current_position], &table[j]);
}
}
控制台:
Input the number of elements to store in the array : 5
Input 5 number of elements in the array :
element - 1: 5
element - 2: 99
element - 3: 22
element - 4: 1
element - 5: 0
The elements in the array before sorting:
element - 1 : 5
element - 2 : 99
element - 3 : 22
element - 4 : 1
element - 5 : 0
错误:
Segmentation fault (core dumped)
有什么建议吗?我的函数结构是否正确,函数参数是否正确?对于排序中的代码,我 100% 确定这是正确的。
【问题讨论】:
-
您已经发布了几个这样的问题。是时候开始学习如何使用调试器来诊断这些错误了。盯着代码看不是很有效,尤其是对于非专家而言,并且每次都询问 StackOverflow 并不是一个很好的长期解决方案。
-
其他需要了解的工具是 malloc 调试器(例如 valgrind)或其他内存清理器(例如 gcc -fsanitize=address)。
-
另外,启用编译器警告,和/或尝试提供比当前版本更好的警告的编译器。 gcc 对
if (*table[j] < *table[current_position]);发出警告,其中尾随分号导致它不执行您想要的操作,并且以下行无条件执行。 (教训:程序中“100% 确定正确”的部分通常是错误所在。:-) -
@NateEldredge 感谢您的建议
-
回滚以免隐藏证据。这不是代码需要修复的地方:它在您自己的机器上。