2d数组中'\ 0'的问题

时间:2016-11-02 20:29:24

标签: c arrays

出于某种原因,当我执行案例1时,我被分配了下午4点的时间,因此它在i的前3个实例中找不到\ 0,但是在第4个实例中找到它。关于null字符如何与2d数组一起工作,我只是有点困惑,它是否默认存储在每一行中,是否需要添加?我想要一个带有5个不同插槽的5x20阵列用于名称。提前致谢

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int i;
    int j;
    int total=0;
    int opt;
    int time;
    char x[5][20];
    char name[20];

    printf("----MAIN MENU----\n");
    printf("1: Request a lesson\n");
    printf("2: Cancel a lesson\n");
    printf("3: See available lessons\n");
    printf("4: List all names starting with a letter\n"); 
    printf("9: Quit\n");


    for(;;)
    {
        scanf("%d",&opt);
        switch(opt)
        {
            case 1:
                printf("please enter your name\n");
                scanf("%s",name);

                //if schedule is full
                if(total==5)
                {   
                    printf("Sorry, the teacher is too busy, try again tomorrow.\n");
                }


                //opening in schedule
                else
                    for(i=0;i<5;i++)
                        if (x[i][0]=='\0')
                        {
                            strcpy(x[i], name);
                            total++;
                            printf("You have been assigned the time %dpm\n",i+1);
                            break;
                        }

                break;

1 个答案:

答案 0 :(得分:0)

Jeff Mercado是正确的,操作。如果不初始化这些数组,则会有未定义的行为。我建议你在每个第一个位置插入零字符'\ 0',以使它与你已经完成的代码保持一致。你可以在你的主要功能上做到这一点:

for (i = 0; i < 5; i++) x[i][0] = '\0';