【问题标题】:Error Assignment makes pointer from integer without a cast [enabled by default]错误赋值使指针从整数而不进行强制转换[默认启用]
【发布时间】:2015-05-09 14:31:33
【问题描述】:

我对 C 编程很陌生。我在编译我的程序时遇到了这个错误。我试图在互联网上寻找解决方案,但无济于事。报错就行了num = rand()%20;

char* getParameter(char *name)
 {
   char *num;

   char *buffer;


   if(strcmp(name,"Trainingsprogramm")){
    srand (time(NULL));
     num = rand()%20;;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"Personnenummer")){
     srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"Tretzustand")){
     srand (time(NULL));
     srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"Tretleistung")){
     srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"Drehzahl")){srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"Geschwindigkeit")){srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"GefahreneDistanz")){srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"RealeKJoule")){srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"AktuellerPuls")){srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"MomentanerGang")){srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"RelaxBetrieb")){srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}else if(strcmp(name,"VerbrauchteKJoule")){srand (time(NULL));
      num = rand()%20;
    sprintf(buffer,"%d",num);
}

return buffer;

}

【问题讨论】:

  • char *num;更改为int num;,为buffer分配内存,在main开头调用一次srand
  • 为什么要连续调用srand?

标签: c


【解决方案1】:

尝试从num 的声明中删除星号。

char *num; // <<< This is a pointer to char declaration
char num; // <<< This is a char

int num; // <<< But this is probably what you meant/wanted!

【讨论】:

  • 谢谢,但我有一个字符缓冲区,这就是我选择字符指针的原因...是否还有另一个函数可以像 rand 一样用于字符而不是整数。谢谢!!
  • 看看this SO answer,然后再查找我脑海中闪现的第一件事,即itoa。这是一个简单的功能,你甚至可以implement it yourself
【解决方案2】:

赋值使指针从整数...

 char *num;
 ...
 num = rand()%20;

代码尝试将rand()的整数结果赋值给字符指针num

从您到目前为止显示的代码中,将num 更改为整数,例如

 int num;

会解决这个问题的。

【讨论】:

  • 谢谢,但我有一个字符缓冲区,这就是我选择字符指针的原因...是否还有另一个函数可以像 rand 一样用于字符而不是整数。谢谢!!
  • @user3628617:你指的是哪个缓冲区?
  • @user3628617 关于printf()(和朋友)的工作方式,您可能想在此处访问 RTFM:man7.org/linux/man-pages/man3/printf.3.html
  • 我指的是我用来接收数据的缓冲区...它不包含在我发布的代码中...
【解决方案3】:

rand() 返回一个int,并对其应用% 运算符也返回一个int - 您应该将此结果保存在int,而不是char*

int num;
char *buffer;

【讨论】:

    猜你喜欢
    • 2013-12-14
    • 2016-08-20
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多