Dylan Kertson Dylan Kertson - 1 year ago 66
C Question

Problems with '\0' in 2d array

For some reason, when I execute case 1, I am assigned the time 4pm, so it doesn't find the \0 in the first 3 instances of i, but finds it on the fourth. I am just a little confused on how the null character works with a 2d array, is it stored by default in every row, does it need to be added? I am trying to have a 5x20 array with 5 different slots for names. Thanks in advance

#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");

case 1:
printf("please enter your name\n");

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

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


Answer Source

Jeff Mercado is correct, op. You will have undefined behavior if you don't initialize those arrays. I suggest you insert the nul character '\0' on every first position, to make it coherent with the code you had already done. You could do that on your main function:

for (i = 0; i < 5; i++) x[i][0] = '\0';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download