0
#include <stdio.h>
#include <stdlib.h>

struct the_struct
{
 char FirstName[20];
 char LastName[32];
 int  Score[20];
};
int main ()
{
int i,n;
struct the_struct *ptr[100];
printf("how many students?\n");
scanf("%d",&n);
while (i<=n);
   {
   i==0;
   ptr[i] = malloc(sizeof(struct the_struct));
   printf("Enter First Name \n");
   scanf("%s",ptr[i]->FirstName);
   printf("Enter Last Name \n");
   scanf("%s",ptr[i]->LastName);
   printf("Enter Score? \n");
   scanf("%s",ptr[i]->Score);
   printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
   i++;
   }

}

hey guys, so when i enter the first input, it goes only once without going on for the number the user inputs, i tried the for loop but same result. still learning C so my apology if i misunderstood something.

Thanks in advance.

2
  • 3
    get rid of the ; after while(i<=n) Commented Apr 27, 2014 at 1:43
  • When i remove the ; when it asks for number of students it ends the program, but it allows me to enter a letter as a first name and ignoring the student number. Commented Apr 27, 2014 at 1:47

2 Answers 2

1

Your while loop is problematic. You could rewrite it as:

for (i = 0; i < n; ++i)
{
   ptr[i] = malloc(sizeof(struct the_struct));
   printf("Enter First Name \n");
   scanf("%s",ptr[i]->FirstName);
   printf("Enter Last Name \n");
   scanf("%s",ptr[i]->LastName);
   printf("Enter Score? \n");
   scanf("%s",ptr[i]->Score);
   printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
}

And since you use %s to read and print Score, you should declare it as char Score[20]; instead of int.

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

1 Comment

that worked!! i'm just printing to know the input is working or not. Thanks!!
0

The problem is that i is uninitialized. Therefore, the loop while (i <= n) has undefined behavior, and can end at any time.

Add int i = 0 initializer to fix this problem.

Notes:

  1. i == 0 expression at the beginning of the loop has no effect
  2. Since i starts at zero, your while loop should be while (i < n), not <=.
  3. You should check the results of scanf to see if the user entered something meaningful
  4. You should specify the size of the array into which you read a string, e.g. scanf("%31s",ptr[i]->LastName); This prevents buffer overruns.

2 Comments

i changed the while loop like you said, same result. tried also the for loop same result.
@Ankosh You need to remove the semicolon after your loop, too. Here is a demo

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.