NULL一个空字符和一个换行符之间的概念区别和相似之处,即'\0' 和'\n' 你能解释它们与整数和字符数据类型变量和数组的相关性吗?
作为参考,这里是一个读取和写入 2d char 数组的程序示例片段
程序代码 1:
int main()
{
char sort(),stuname(),swap(),(*p)(),(*q)();
int n;
p=stuname;
q=swap;
printf("Let the number of students in the class be \n");
scanf("%d",&n);
fflush(stdin);
sort(p,q,n);
return 0;
}
char sort(p1,q1,n1)
char (*p1)(),(*q1)();
int n1;
{
(*p1)(n1);
(*q1)();
}
char stuname(int nos) // number of students
{
char name[nos][256];
int i,j;
printf("Reading names of %d students started--->\n\n",nos);
name[0][0]='k'; //initialising as non NULL charecter
for(i=0;i<nos;i++) // nos=number of students
{
printf("Give name of student %d\n",i);
for(j=0;j<256;j++)
{
scanf("%c",&name[i][j]);
if(name[i][j]=='\n')
{
name[i][j]='\0';
j=257;
}
}
}
printf("\n\nWriting student names:\n\n");
for(i=0;i<nos;i++)
{
for(j=0;j<256&&name[i][j]!='\0';j++)
{
printf("%c",name[i][j]);
}
printf("\n");
}
}
char swap()
{
printf("Will swap shortly after getting clarity on scanf and %c");
}
上面的代码运行良好,而给出的相同逻辑略有不同,但没有给出适当的输出。这是代码
程序代码 2:
#include<stdio.h>
int main()
{
char sort(),stuname(),swap(),(*p)(),(*q)();
int n;
p=stuname;
q=swap;
printf("Let the number of students in the class be \n");
scanf("%d",&n);
fflush(stdin);
sort(p,q,n);
return 0;
}
char sort(p1,q1,n1)
char (*p1)(),(*q1)();
int n1;
{
(*p1)(n1);
(*q1)();
}
char stuname(int nos) // number of students
{
char name[nos][256];
int i,j;
printf("Reading names of %d students started--->\n\n",nos);
name[0][0]='k'; //initialising as non NULL charecter
for(i=0;i<nos;i++) // nos=number of students
{
printf("Give name of student %d\n",i);
***for(j=0;j<256&&name[i][j]!='\0';j++)***
{
scanf("%c",&name[i][j]);
/*if(name[i][j]=='\n')
{
name[i][j]='\0';
j=257;
}*/
}
}
printf("\n\nWriting student names:\n\n");
for(i=0;i<nos;i++)
{
for(j=0;j<256&&name[i][j]!='\0';j++)
{
printf("%c",name[i][j]);
}
printf("\n");
}
}
char swap()
{
printf("Will swap shortly after getting clarity on scanf and %c");
}
这里还有一个相同程序的实例没有给出下面给出的正确输出
程序代码 3:
#include<stdio.h>
int main()
{
char sort(),stuname(),swap(),(*p)(),(*q)();
int n;
p=stuname;
q=swap;
printf("Let the number of students in the class be \n");
scanf("%d",&n);
fflush(stdin);
sort(p,q,n);
return 0;
}
char sort(p1,q1,n1)
char (*p1)(),(*q1)();
int n1;
{
(*p1)(n1);
(*q1)();
}
char stuname(int nos) // number of students
{
char name[nos][256];
int i,j;
printf("Reading names of %d students started--->\n\n",nos);
name[0][0]='k'; //initialising as non NULL charecter
for(i=0;i<nos;i++) // nos=number of students
{
printf("Give name of student %d\n",i);
***for(j=0;j<256&&name[i][j]!='\n';j++)***
{
scanf("%c",&name[i][j]);
/*if(name[i][j]=='\n')
{
name[i][j]='\0';
j=257;
}*/
}
name[i][i]='\0';
}
printf("\n\nWriting student names:\n\n");
for(i=0;i<nos;i++)
{
for(j=0;j<256&&name[i][j]!='\0';j++)
{
printf("%c",name[i][j]);
}
printf("\n");
}
}
char swap()
{
printf("Will swap shortly after getting clarity on scanf and %c");
}
为什么程序代码 2 和程序代码 3 不像代码 1 那样工作?