简体   繁体   English

指向 C 中数组的第一个元素

[英]Pointing to first element of an array in C

I'm sorry if this questions has already been asked, I searched a bit before posting, but couldn't find an answer to it.如果已经有人问过这个问题,我很抱歉,我在发帖前搜索了一些,但找不到答案。

I have this code:我有这个代码:

#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;
}

When I run this program I have this output:当我运行这个程序时,我有这个输出:

0 17 18 19 20 21 22 23 24 25 0 17 18 19 20 21 22 23 24 25

I can't understand why the first print is the position of the first element in the array and not the first element itself.我不明白为什么第一个打印是数组中第一个元素的位置而不是第一个元素本身。 Can someone please explain me?有人可以解释一下吗?

choice is a char and the correct conversion specifier to be used in scanf is c and not s . choice是一个char并且要在scanf使用的正确转换说明符是c而不是s

One must also be careful when using scanf interspersed with printf statements which print new lines ( \\n ).在使用scanf时也必须小心,其中散布着打印新行 ( \\n ) 的printf语句。

When scanf has the conversion specifier c , then it will interpret any whitespace as a character and will not wait for the actual input.scanf具有转换说明符c ,它会将任何空格解释为字符,并且不会等待实际输入。 So the scanf here should make allowance for the whitespace character by including a leading blank space.所以这里的scanf应该通过包含一个前导空格来考虑空格字符。

So the scanf statement should be:所以scanf语句应该是:

scanf(" %c", &choice);

It is also a good practice to check the return value of scanf before proceeding further in the program.在程序中继续进行之前检查scanf的返回值也是一个很好的做法。 As per the standard, scanf returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.根据标准, scanf返回分配的输入项的数量,在早期匹配失败的情况下,该数量可能少于提供的数量,甚至为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM