Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c - I can not input the names into the char array using scanf

I can not use scanf to enter a name in stdnames array. when compiled it had no error , but as soon as i enter a name and then press enter to write the other name it gives an error and shuts the program. How should I go about it ?

int main(int argc, char* argv[])
{
  float marks[50];
  /*char *stdnames[100]={"Arvind Thillainathan","Robert Lang"};*/
 //I want to stores names like the above one
  char *stdnames[100];
  int totalNames = 0;
  int i = 0, w=0,h=0;

 printf("How many names do you want to enter ??
");
 scanf("%d",&totalNames);
 assert(totalNames != 0);

 for(int count = 0; count < totalNames; count++)
 {
     printf("Enter name of student
");
     scanf("%s",stdnames[count]);
 //From here the problem starts
 }
 getres(marks,totalNames);

 for(i = 0; i < totalNames; i++) 
      {
        int v = 1;
        printf("
");
        printf("IELTS Marks of %s

",stdnames[i]);
        for(h = w; h < w+5; h++)
           {
            if(v==1)
            {
                printf("Listening : %0.1f
", marks[h]);
            }
            else if(v==2)
            {
                printf("Reading   : %0.1f
", marks[h]);    
            }
            else if(v==3)
            {
                printf("Writing   : %0.1f
", marks[h]);    
            }
            else if(v==4)
            {
                printf("Speaking  : %0.1f
", marks[h]);    
            }
            else
            {
                printf("Overall   : %0.1f

", marks[h]);
            }
            v++;
            //if(h==10)
            //{
            //  break;
            //}
        }
        w+=5;
}
return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By

char *stdnames[100];

you got an array of (pointers to char).

The NEXT BIG QUESTION is

Who will allocate memory for each of these pointers?

A small answer would be - You have to do it yourself like below :

stdnames[count]=malloc(100*sizeof(char)); // You may replace 100 with desired size

or

stdnames[count]=malloc(100); // sizeof(char) is almost always 1

You need to put this line before the scanf statement.

Note: Don't forget to free the allocated memory once these variables become irrelevant. Do it like :

free(stdnames[count]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...