我無法使用scanf將名稱輸入到char數組中

[英]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 ?

我無法使用scanf在stdnames數組中輸入名稱。編譯時它沒有錯誤,但只要我輸入一個名字,然后按回車鍵寫另一個名稱就會出錯並關閉程序。我該怎么辦呢?

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 个解决方案

#1


1  

By

char *stdnames[100];

you got an array of (pointers to char).

你有一個數組(指向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.

您需要將此行放在scanf語句之前。

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

注意:一旦這些變量變得無關緊要,不要忘記釋放已分配的內存。這樣做:

free(stdnames[count]);

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/05/11/72f10a3b7cc2a3abbb3ccc403335e3a5.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com