我在Fedora下使用g ++来编译一个openGL项目,该项目有以下几行:
textureImage = (GLubyte**)malloc(sizeof(GLubyte*)*RESOURCE_LENGTH);
Run Code Online (Sandbox Code Playgroud)
编译时,g ++错误说:
error: ‘malloc’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
添加#include <cstdlib>
不能解决错误.
我的g ++版本是: g++ (GCC) 4.4.5 20101112 (Red Hat 4.4.5-2)
use*_*653 31
你应该使用new
C++代码,而不是malloc
它new GLubyte*[RESOURCE_LENGTH]
.当你#include <cstdlib>
将它加载malloc
到命名空间中时std
,所以请参考std::malloc
(或#include <stdlib.h>
改为).
如何尽可能简单地重现此错误:
将此代码放在main.c中:
#include <stdio.h>
int main(){
int *foo;
foo = (int *) std::malloc(sizeof(int));
*foo = 50;
printf("%d", *foo);
}
Run Code Online (Sandbox Code Playgroud)
编译它,它返回一个编译时错误:
el@apollo:~$ g++ -o s main.c
main.c: In function ‘int main()’:
main.c:5:37: error: ‘malloc’ was not declared in this scope
foo = (int *) malloc(sizeof(int));
^
Run Code Online (Sandbox Code Playgroud)
修复如下:
#include <stdio.h>
#include <cstdlib>
int main(){
int *foo;
foo = (int *) std::malloc(sizeof(int));
*foo = 50;
printf("%d", *foo);
free(foo);
}
Run Code Online (Sandbox Code Playgroud)
然后它编译并正确运行:
el@apollo:~$ g++ -o s main.c
el@apollo:~$ ./s
50
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
74109 次 |
最近记录: |