【发布时间】:2016-02-09 19:36:38
【问题描述】:
我为冒泡排序编写了一个程序,它显示了一个运行时错误,说“NULL Pointer Assignment”。代码如下:
#include <stdio.h>
void main()
{
int a[6], j = 0, count = 0, i, temp;
printf("Enter the number");
for(i = 0; i< 4; i++)
{
scanf("%d", &a[i]);
}
while(count < 4)
{
for(i = 0; i < 4; i++)
{
if(a[i] < a[++j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
count++;
}
printf("The sorted array is");
for(i = 0; i < 4; i++)
{
printf("\n%d\n", a[i]);
}
getchar();
}
但是当我尝试下面的代码时,它运行成功了。
#include <stdio.h>
void main()
{
int a[6], count=0, i, temp;
printf("Enter the number");
for(i = 0; i < 4; i++)
{
scanf("%d", &a[i]);
}
while(count<4)
{
for(i = 0; i < 4; i++)
{
if(a[i] < a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
count++;
}
printf("The sort array is");
for(i = 0; i < 4; i++)
{
printf("\n%d\n", a[i]);
}
getchar();
}
所以我需要我的代码显示错误的原因,以及第二个代码工作的原因。我是 C 的新手,所以请简单地向我解释一下原因。
【问题讨论】:
-
这是一个学习如何使用调试器的绝佳机会,调试器是程序员非常重要的工具。如果你在调试器中运行你的程序,它会捕获崩溃之类的东西,并在崩溃的位置停止。从那里您可以将函数调用堆栈向上移动到您的代码(如果崩溃尚未出现)并检查变量的值。即使您自己无法解决问题,那么至少请编辑您的问题以向我们展示在哪里崩溃发生在您的代码中。
-
使用适当的缩进会极大地提高代码的可读性。
-
顺便说一下,在第一个程序中,您的内部循环在排序时,变量
j将way 超出数组a的范围,导致未定义的行为。在您的第二个程序中,您将在排序时将 fifth 元素包含在数组中,该元素已初始化,因此其值为 indeterminate,再次导致 未定义的行为. -
您知道一次可以扫描多个变量,像
scanf("%d %d %d %d", &var1, &var2, &var3, &var4)这样的事情? -
@JoachimPileborg 所说的。没有任何明显的调试尝试总是得到我的反对,无论从查看源代码来看,这个错误多么微不足道或多么明显。
标签: c bubble-sort