正确使用malloc()

mus*_*afa 0 c malloc

我在用C语言编写代码时使用malloc,但我得到了

[警告]内置函数'malloc'的冲突类型

编译时这个警告.

这是我使用的代码:

starttimer(AorB,increment)
int AorB;  /* A or B is trying to stop timer */
float increment;
{

 struct event *q;
 struct event *evptr;
 char *malloc();

 if (TRACE>2)
    printf("          START TIMER: starting timer at %f\n",time);
 /* be nice: check to see if timer is already started, if so, then  warn */
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next)  */
   for (q=evlist; q!=NULL ; q = q->next)  
    if ( (q->evtype==TIMER_INTERRUPT  && q->eventity==AorB) ) { 
      printf("Warning: attempt to start a timer that is already started\n");
      return;
      }

/* create future event for when timer goes off */
   evptr = (struct event *)malloc(sizeof(struct event));
   evptr->evtime =  time + increment;
   evptr->evtype =  TIMER_INTERRUPT;
   evptr->eventity = AorB;
   insertevent(evptr);
} 
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Jon*_*art 5

你需要#include <stdlib.h>,并删除你的虚假声明:char *malloc();

此外,您需要找到更新的C参考! K&R函数声明语法已经过时很长时间了.

考虑改变:

starttimer(AorB,increment)
int AorB;  /* A or B is trying to stop timer */
float increment;
{
Run Code Online (Sandbox Code Playgroud)

(看上去很好的)ANSI C标准:

int starttimer(int AorB, float increment) {
Run Code Online (Sandbox Code Playgroud)

  • 更精确一点:自1989年ANSI C标准发布以来,K&R函数声明已经过时了.**这是大约25年前的事情.**令人惊讶的是,编译器仍然容忍它. (2认同)