0

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]);
 }
5
  • 1
    Correcting your indenting would make the code more readable Commented Jan 7, 2022 at 20:32
  • You created an array of characters and not pointers. Pointers are used to reference “strings” of characters. I’m not sure what j does and is currently not set or manipulated so you’ll likely run into storage corruption. Commented Jan 7, 2022 at 20:36
  • 1
    printf("courses are %s",courses[p]) outputs one string, but the code does not enter any data for courses[p], only up to courses[p-1]. Commented Jan 7, 2022 at 20:39
  • In addition to the unintialised j value, the last printf is also wrong. p is not a valid index at that point and if you want to print out all the courses you need another for loop to print each of the courses strings. Commented Jan 7, 2022 at 20:40
  • Link123, did you write this code? Commented Jan 7, 2022 at 20:54

1 Answer 1

1
int main()
{
    char courses[60][100];
    char ans ='y';
    size_t  i = 0;

    do
    {
        printf("Enter course:\n");
        scanf("%99s", 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

Sign up to request clarification or add additional context in comments.

1 Comment

@chux-ReinstateMonica and courses[i] not &courses[i]. Copy paste

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.