c++ - C 与 C++ 中的指针

标签 c++ c pointers

<分区>

Possible Duplicate:
Why does C++ require a cast for malloc() but C doesn’t?

这段特殊的代码在 C 中运行良好,但在编译为 C++ 程序时会出现编译错误。

#include<stdio.h>
#include<stdlib.h>
int main(){
    int (*b)[10];
    b = calloc(20, sizeof(int));
    return 0;
}

C++编译错误是:

test.cpp: In function ‘int main()’:
test.cpp:9:28: error: invalid conversion from ‘void*’ to ‘int (*)[10]’ [-fpermissive]

知道可能是什么原因吗?

最佳答案

虽然在 C 中您可以将 void 指针隐式转换为其他指针类型,但在 C++ 中是不允许的,您需要显式转换它:

b = (int (*)[10])calloc(20, sizeof(int));

关于c++ - C 与 C++ 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13226575/

相关文章:

c++ - 函数指针

c - 在C中读取邮件假脱机

c++ - 在 C++ 中初始化静态指针

python - 用于指向类的指针的 STL 映射的 SWIG 类型映射

c - 从不兼容的指针类型传递参数

c++ - ld: 未找到体系结构 x86_64 行::AddColumn 的符号

c++ - string::find 未找到匹配项

C++0x 实现猜测?

C的空字符,引用 "Learn C the Hard Way"的Ex.9

c - 使用gdb获取所有当前使用的变量的地址