malloc分配给指针

时间:2012-12-12 15:46:42

标签: c++ c pointers malloc

我有这个问题。

我有以下声明。

int *a;
a=malloc(100);

我收到以下错误:

  

错误:无效转换为'void *'到'int *'[-fpermissive]

有关此的任何提示吗?

3 个答案:

答案 0 :(得分:11)

您正在将代码编译为C ++,其中您使用的代码无效。但对于C来说,它是有效的,而你是should not add any cast

但请注意,malloc()的参数位于char s中,因此“100”有点随机。如果你想要100个整数,请执行:

a = malloc(100 * sizeof *a);

答案 1 :(得分:0)

在C ++中编写C兼容代码时,你必须使用malloc,因为有些纯C库会转到它free,我建议你写一个快速输入的malloc:

template<typename T>
T* typed_malloc( size_t count = 1 ) {
  return reinterpret_cast<T*>( malloc(sizeof(T)*count) );
}

然后你可以这样使用:

int *a;
a=typed_malloc<int>(100);

创建一个大小为100 int s的缓冲区。

添加一些额外的东西,比如防止用这种方式创建具有非平凡析构函数的类(正如你期望它们free d而不被破坏),也可能会被推荐。

答案 2 :(得分:-4)

malloc返回一个void *指针。

你应该这样做:

a=(int*)malloc(100);

BTW:此声明分配100Bytes而不是100 ints。 LE:如果你用gcc编译,这不是必需的。如果您正在使用g ++进行编译,那么这是必须的。