我有以下代码在堆上创建一个大的二维数组:
static unsigned char** storagebuffer;
storagebuffer = (unsigned char*) malloc(128 *sizeof(unsigned char *));
for (int i = 0; i < 128; i++)
storagebuffer[i] = malloc(8192 *sizeof(unsigned char));
使用GCC
可以编译并正常工作,但是当我在Visual C++
文件中执行此操作时,会出现以下错误:
processing.cpp(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>processing.cpp(11): error C2040: 'storagebuffer' : 'int' differs in levels of indirection from 'unsigned char **'
1>processing.cpp(11): error C2440: 'initializing' : cannot convert from 'unsigned char *' to 'int'
1> There is no context in which this conversion is possible
1>processing.cpp(13): error C2059: syntax error : 'for'
1>processing.cpp(13): error C2143: syntax error : missing ')' before ';'
1>processing.cpp(13): error C2143: syntax error : missing ';' before '<'
1>processing.cpp(13): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>processing.cpp(13): error C2143: syntax error : missing ';' before '++'
1>processing.cpp(13): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>processing.cpp(13): error C2086: 'int i' : redefinition
1> processing.cpp(13) : see declaration of 'i'
1>processing.cpp(13): error C2059: syntax error : ')'
如何使用 Visual C++ 执行此操作?
最佳答案
问题在于代码在 MS VS 中编译为 C++ 代码(请参阅错误消息 C++ 不支持 default-int
)。 C++ 不允许从类型 void *
到任何其他类型的指针的隐式转换。
storagebuffer[i] = malloc(8192 *sizeof(unsigned char));
^^^^^^
您必须显式转换指针。
您应该在 MS VS 中将代码编译为 C 代码,或者指定转换运算符。
storagebuffer[i] = ( unsigned char * )malloc(8192 *sizeof(unsigned char));
或
storagebuffer[i] = reinterpret_cast<unsigned char *>( malloc(8192 *sizeof(unsigned char)) );
请考虑此声明
storagebuffer = (unsigned char*) malloc(128 *sizeof(unsigned char *));
必须写成
storagebuffer = (unsigned char**) malloc(128 *sizeof(unsigned char *));
我认为这只是一个拼写错误。
关于c - 二维数组的 malloc 在 GCC 中有效,但在 Visual C++ 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25054795/