I’m new to c and don’t really understand how 2d arrays work. When the code is executed it prompts for me to enter a course and then when the loop is broken the print statement doesn’t show what I inputted.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char courses[60][100];
char ans ='y';
int i=0;
int p,j;
while (ans == 'y'){
printf("Enter course:\n");
for (p=0;p<j;p++)
scanf("%s", &courses[p]);
getchar();
i++;
printf("Would you like to enter another course? (y or n) \n");
ans = getchar();
}
printf("courses are %s",courses[p]);
}
>Solution :
int main()
{
char courses[60][100];
char ans ='y';
size_t i = 0;
do
{
printf("Enter course:\n");
scanf("%s", &courses[i]);
getchar();
i++;
printf("Would you like to enter another course? (y or n) \n");
ans = getchar();
}while(ans == 'y');
for(size_t p = 0; p < i; p++)
printf("courses are %s\n",courses[p]);
}
https://godbolt.org/z/EKqEq8aos