I'm trying to read some char
arrays from keyboard, but every time the program crashes.
I would like to know how I can comfortably input and store char
arrays from keyboard.
int main()
{
int i;
char *days[7];
for(i=0;i<7;i )
{
scanf("%s", days[i]);
}
for(i=0;i<7;i )
{
printf("%s\n", days[i]);
}
return 0;
}
CodePudding user response:
char *days[7]
declares an array of pointers. Unless initialized with valid address, they point to invalid memory locations. So, when you want to write to them, they invoke undefined behaviour.
You need to ensure to make them point towards valid memory (locations), before you use them.
CodePudding user response:
Yuo declare an aaray of pointer to char
but those pointers do not reference valid memory.
You need to allocate memory for them:
int main(void)
int i;
char *days[7];
for(i=0;i<7;i )
{
days[i] = malloc(MAXLENGTH);
scanf("s", days[i]);
}
for(i=0;i<7;i )
{
printf("%s\n", days[i]);
free(days[i]);
}
return 0;
}
or you can
int main(void)
{
int i;
char days[7][MAXLENGTH];
for(i=0;i<7;i )
{
scanf("s", days[i]);
}
for(i=0;i<7;i )
{
printf("%s\n", days[i]);
}
return 0;
}