#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char a[3][7];
char temp[40];
int i=0 ;
while(i<3&&gets(temp)){
if(temp[0]!='q'){
printf("%s doesn't begin with q",temp);
}
else{
strncpy(a[i],temp,6);
a[i][6]='\0';
i++;
}
}
for(i=0;i<3;i++){
puts(a[i]);
}
return 0;
}
a[i][6]='\0';
为什么这里是a[i][6]='\0';不是a[i][7]='\0', a[i][6]不应该是temp里面的一个字符吗?我把a[i][6]='\0'改成a[i][7]='\0'有陷入死循环了,这是什么原因呢?
数组下标是从
0
开始的代表3个长度为7的char数组,每一个数组的下标范围是
a[i][0] ... a[i][6]
填充了
a[i]
的前6个字节:a[i][0] ... a[i][5]
a[i][6]
是a[i]
的最后一个元素,a[i][7]
就溢出了