c - 二维数组的 malloc 在 GCC 中有效,但在 Visual C++ 中无效

标签 c visual-c++ malloc

我有以下代码在堆上创建一个大的二维数组:

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/

相关文章:

c++ - 直接渲染到 WASAPI 时,两个流之一没有音频输出

linux - visual c++ for linux 停止(tty 输入)

c - realloc() C语言改变int数组中的值

c - 将内存分配给包含结构的节点

c - 将节点插入双链表时出现段错误

无法在cgi中执行外部命令

c - 从 OCI 中的绑定(bind)名称获取绑定(bind)位置

c++ - 如何使用 OpenCV 中可用的压缩算法?

c++ - 应用纹理另一个问题directx c++

c - 为什么我不能通过它的指针访问这个结构?