C 中的 NULL 混淆
NULL confusion in C
我正在创建一个简单的 "ascending" 程序。当我在 int
的数组中找到最小的 int
时,我想用其他值替换它,这样它就不会再次作为数组中的最小数字出现。为此,我分配了 int
NULL
。但现在的结果并不如预期。
如果我做错了什么请告诉我。如果是这样,那么我应该用 int
的值替换什么?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[10],b,c=0,d=0;
printf("Enter number of values you want to enter \n");
scanf("%d",&b);
printf("Enter values \n");
for(int i=0;i<b;i++)
scanf("%d",&a[i]);
while(c<b)
{
for(int k=0;k<b;k++)
{
for(int j=0;j<b;j++)
{
if(a[k] > a[j])
{
d=1;
}
}
if(d!=1 && a[k]!=NULL)
{
c++;
printf("%d ",a[k]);
a[k]='[=10=]' ; //assigning it as NULL
}
if(c >= b)
break;
d=0;
}
}
getch();
}
在 C 和相关语言中 int
s 不是 "nullable" - 您可以使用特殊值代替,例如远远超出输入数据预期范围的值,例如 INT_MAX
:
#include <limits.h> // required header for INT_MAX et al
...
if(d!=1 && a[k]!=INT_MAX)
{
c++;
printf("%d ",a[k]);
a[k]=INT_MAX
}
不过,回到绘图板看看您是否可以想出不需要特殊值的更好算法可能是个好主意。
阅读NULL和0与'\0'的区别here。当您尝试 a[k]!=NULL
.
时出现类型不匹配
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int a[10], b, c = 0, d = 0;
int k, j, i;
printf("Enter number of values you want to enter \n");
scanf("%d",&b);
printf("Enter values \n");
for(i = 0;i < b;i++)
scanf("%d",&a[i]);
while(c < b)
{
for(k = 0;k < b;k++)
{
for(j = 0;j < b;j++)
{
if((a[k] > a[j]) && a[j] != 0)
{
d=1;
}
}
if(d != 1 && a[k] != 0)
{
c++;
printf("%d ",a[k]);
a[k] = 0; //assigning it as NULL
}
if(c >= b)
break;
d=0;
}
}
return 0;
getch();
}
此代码解决了问题。
您缺少的是 if((a[k] > a[j]) && a[j] != 0)
中的 a[j] != 0
。另外我不建议这样做,因为如果输入的数组中有 0,它将不起作用。
我正在创建一个简单的 "ascending" 程序。当我在 int
的数组中找到最小的 int
时,我想用其他值替换它,这样它就不会再次作为数组中的最小数字出现。为此,我分配了 int
NULL
。但现在的结果并不如预期。
如果我做错了什么请告诉我。如果是这样,那么我应该用 int
的值替换什么?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[10],b,c=0,d=0;
printf("Enter number of values you want to enter \n");
scanf("%d",&b);
printf("Enter values \n");
for(int i=0;i<b;i++)
scanf("%d",&a[i]);
while(c<b)
{
for(int k=0;k<b;k++)
{
for(int j=0;j<b;j++)
{
if(a[k] > a[j])
{
d=1;
}
}
if(d!=1 && a[k]!=NULL)
{
c++;
printf("%d ",a[k]);
a[k]='[=10=]' ; //assigning it as NULL
}
if(c >= b)
break;
d=0;
}
}
getch();
}
在 C 和相关语言中 int
s 不是 "nullable" - 您可以使用特殊值代替,例如远远超出输入数据预期范围的值,例如 INT_MAX
:
#include <limits.h> // required header for INT_MAX et al
...
if(d!=1 && a[k]!=INT_MAX)
{
c++;
printf("%d ",a[k]);
a[k]=INT_MAX
}
不过,回到绘图板看看您是否可以想出不需要特殊值的更好算法可能是个好主意。
阅读NULL和0与'\0'的区别here。当您尝试 a[k]!=NULL
.
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int a[10], b, c = 0, d = 0;
int k, j, i;
printf("Enter number of values you want to enter \n");
scanf("%d",&b);
printf("Enter values \n");
for(i = 0;i < b;i++)
scanf("%d",&a[i]);
while(c < b)
{
for(k = 0;k < b;k++)
{
for(j = 0;j < b;j++)
{
if((a[k] > a[j]) && a[j] != 0)
{
d=1;
}
}
if(d != 1 && a[k] != 0)
{
c++;
printf("%d ",a[k]);
a[k] = 0; //assigning it as NULL
}
if(c >= b)
break;
d=0;
}
}
return 0;
getch();
}
此代码解决了问题。
您缺少的是 if((a[k] > a[j]) && a[j] != 0)
中的 a[j] != 0
。另外我不建议这样做,因为如果输入的数组中有 0,它将不起作用。