![](/img/trans.png)
[英]Why is pointing to one before the first element of an array not allowed in C?
[英]Pointing to first element of an array in C
如果已经有人问过这个问题,我很抱歉,我在发帖前搜索了一些,但找不到答案。
我有这个代码:
#include<stdio.h>
#include<stdlib.h>
#define ESC 27
typedef struct{
int data[10];
int n;
} tlist;
void menu(){
printf("Options:\n");
printf("1) Show list\n");
printf("ESC) Quit\n");
}
void showList(tlist *list){
int *p;
p = &list->data[0];
if(list->n == 0){
printf("Empty list!\n\n");
}else{
for(int i=0; i<list->n; i++){
printf("%d \n", *p);
p++;
}
}
}
int main(){
char choice;
tlist list;
list.n = 10;
list.data[0] = 16;
list.data[1] = 17;
list.data[2] = 18;
list.data[3] = 19;
list.data[4] = 20;
list.data[5] = 21;
list.data[6] = 22;
list.data[7] = 23;
list.data[8] = 24;
list.data[9] = 25;
do{
menu();
scanf("%s",&choice);
switch(choice){
case '1': showList(&list);
break;
case ESC:
printf("quiting...\n");
break;
default:
printf("Invalid Choice!\n");
break;
}
}while(choice != ESC);
return 0;
}
当我运行这个程序时,我有这个输出:
0 17 18 19 20 21 22 23 24 25
我不明白为什么第一个打印是数组中第一个元素的位置而不是第一个元素本身。 有人可以解释一下吗?
choice
是一个char
并且要在scanf
使用的正确转换说明符是c
而不是s
。
在使用scanf
时也必须小心,其中散布着打印新行 ( \\n
) 的printf
语句。
当scanf
具有转换说明符c
,它会将任何空格解释为字符,并且不会等待实际输入。 所以这里的scanf
应该通过包含一个前导空格来考虑空格字符。
所以scanf
语句应该是:
scanf(" %c", &choice);
在程序中继续进行之前检查scanf
的返回值也是一个很好的做法。 根据标准, scanf
返回分配的输入项的数量,在早期匹配失败的情况下,该数量可能少于提供的数量,甚至为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.