我一直收到关于malloc的错误,我正在尝试找出如何在不在头文件中使用stdlib.h的情况下让这段代码工作。只需要stdio.h,这是可能的吗?因为我完全迷惑了
#include <stdio.h>
void allocate(int* score_array, const int input)
{
int iter;
for(iter = 1;iter <= 11;++iter)
{
if( (input < iter*10) && (input >= (iter-1)*10 ) )
{
++(score_array[iter-1]);
}
}
}
void printf_star(const int len)
{
int iter;
for(iter = 0;iter < len;++iter)
{
printf("*");
}
printf("\n");
}
int main()
{
int iter, size, temp;
int* buffer;
int score_array[11];
for(iter = 0;iter < 11;++iter)
{
score_array[iter] = 0;
}
printf("How many grades will you be entering?\n");
printf("Enter a number between 1 and 100: ");
scanf("%d", &size);
buffer = (int*)malloc(size*sizeof(int));
for(iter = 1;iter <= size;++iter )
{
printf("Getting grade %d. You have %d grade(s) left to enter\n", iter, size-iter+1);
printf("Enter a number between 0 and 100: ");
scanf("%d",&temp);
if( (temp>=0) && (temp <= 100) )
{
buffer[iter-1] = temp;
}
else
{
do
{
printf("Invalid Value!\n");
printf("Getting grade %d. You have %d grade(s) left to enter\n", iter, size-iter+1);
printf("Enter a number between 0 and 100: ");
scanf("%d",&temp);
}
while( (temp < 0) || (temp > 100) );
}
}
for(iter = 1;iter <= size;++iter)
{
allocate(score_array, buffer[iter-1]);
}
for(iter = 0;iter < 11;++iter)
{
printf_star(score_array[iter]);
}
return 0;
}我一直收到这个错误:
hw08.c: In function ‘main’:
hw08.c:56: warning: incompatible implicit declaration of built-in function ‘malloc’发布于 2017-05-04 23:43:00
这只是一个警告,而不是一个实际的错误,所以程序仍然会编译。
要消除该警告,可以在文件中声明malloc:
#include <stdio.h>
extern void * malloc(unsigned long);您也可以只包含stdlib.h,除非您有重要的理由不这样做。
发布于 2017-05-05 00:01:53
头文件仅使用extern关键字定义函数原型。malloc的实际实现驻留在libc中,具体取决于操作系统。
不定义函数/系统调用原型确实是警告,而不是编译时错误,这与许多人在注释中传达的信息相反!

谈到实际的解决方法,如果您希望避免使用#include <stdlib.h>,则需要使用:
#include <malloc.h> (由于使用extern void * malloc(size_t);c89)
致谢@Chris Rouffer!:)
发布于 2017-05-04 23:41:41
如果想要访问malloc()函数,则需要包含stdlib.h,因为它就是在这里定义的。否则,编译器不知道该怎么做。如果你想使用这个函数,你真的应该在你的代码中包含头部,然而,理论上你可以只在你的源代码中粘贴malloc()的实现,然后在那里使用它而不使用头部。然而,这不是一个好主意,因为任何看过代码的人都希望malloc()引用stdlib.h中定义的标准实现。
https://stackoverflow.com/questions/43787270
复制相似问题