【问题标题】:I can not input the names into the char array using scanf我无法使用 scanf 将名称输入到 char 数组中
【发布时间】:2016-09-07 08:57:35
【问题描述】:

我无法使用 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;
}

【问题讨论】:

  • 您正在扫描到一个未分配的对象stdnames[count]。也许先尝试在那里分配一些内存,比如malloc
  • 当你有char *stdnames[100]; 时,你也可能会遇到float marks[50]; 的麻烦,尽管输入标记的循环有点模糊。
  • 没有“字符数组”。你的意思是指向char的指针数组?
  • @arvind-dexter-thillainathan :考虑在代码中包含getres(marks,totalNames) 的定义。

标签: c arrays for-loop char scanf


【解决方案1】:

char *stdnames[100];

你有一个数组(指向 char 的指针)。

下一个大问题是

谁将为每个指针分配内存?

一个小答案是 - 你必须像下面这样自己做:

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

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

您需要将此行放在scanf 语句之前。

注意:一旦这些变量变得无关紧要,不要忘记释放分配的内存。这样做:

free(stdnames[count]);

【讨论】:

  • 那个黑体字眼睛疼。而sizeof(char) 是无用的,因为它永远不会产生除1 以外的东西。
  • @Olaf :也伤害了我的。改变了:D
  • 谢谢(对我来说还是有点太大声了,但我可以忍受 - 无论如何都必须阅读 Word-Docs 和 PPT)。内容还有其他问题。
  • 嗯,那是正确的(并且与类型无关),但实际上我想知道为什么不直接删除该术语?
  • @sjsam 谢谢伙计,它工作得很好。我刚开始 C. malloc 的确切目的是什么?
猜你喜欢
  • 2015-04-06
  • 2021-08-17
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
  • 2019-04-02
  • 1970-01-01
相关资源
最近更新 更多