I can not input the names into the char array usin

2019-09-26 02:24发布

问题:

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 ??\n");
 scanf("%d",&totalNames);
 assert(totalNames != 0);

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

 for(i = 0; i < totalNames; i++) 
      {
        int v = 1;
        printf("\n");
        printf("IELTS Marks of %s\n\n",stdnames[i]);
        for(h = w; h < w+5; h++)
           {
            if(v==1)
            {
                printf("Listening : %0.1f\n", marks[h]);
            }
            else if(v==2)
            {
                printf("Reading   : %0.1f\n", marks[h]);    
            }
            else if(v==3)
            {
                printf("Writing   : %0.1f\n", marks[h]);    
            }
            else if(v==4)
            {
                printf("Speaking  : %0.1f\n", marks[h]);    
            }
            else
            {
                printf("Overall   : %0.1f\n\n", marks[h]);
            }
            v++;
            //if(h==10)
            //{
            //  break;
            //}
        }
        w+=5;
}
return 0;
}

回答1:

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]);