【问题标题】:"Invalid conversion" error when using malloc? [duplicate]使用 malloc 时出现“无效转换”错误? [复制]
【发布时间】:2012-03-15 22:45:00
【问题描述】:

可能重复:
invalid conversion from void*' to char*' when using malloc?

我正在尝试使用指针在内存中动态分配一个矩阵,但我不断收到错误消息:

|122|错误:从 'void*' 到 'int**' 的无效转换|

|124|错误:从 'void*' 到 'int*' 的无效转换|

这是我的代码,我看不出我做错了什么...这种“void*”转换对我来说没有意义...

   int i,j;
   int **a;
   int c = 2;
 

   /* Form the matrix */
   a = malloc((nxy+1)*sizeof(int *));
   for (i=0;i<=nxy;i++)
      a[i] = malloc((nxy+1)*sizeof(int));
   
   for (i=0;i<=nxy;i++)
      for (j=0;j<=nxy;j++)
         a[i][j] = 0;
   

【问题讨论】:

  • 你确定用 C 编译器而不是 C++ 编译器编译吗?
  • 添加到@CharlesBailey 评论。你是在 Visual Studio 的 .cpp 文件中编译它吗?
  • 我实际上在使用 Code::Blocks

标签: c pointers matrix


【解决方案1】:

您正在使用 C++ 编译器编译程序。你有两个选择:

  1. 不要那样做。使用 C 编译器。
  2. malloc() 转换返回值。

【讨论】:

  • 什么意思?如果它只是 NULL 内存的一部分,我应该如何转换返回值?
  • a = (int **)malloc(....)。我不明白你的问题。
  • 没关系,我只是把脑袋弄得一团糟,哈哈,我现在明白了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-25
  • 2017-06-06
  • 2017-07-20
  • 1970-01-01
  • 2014-05-02
  • 2020-10-31
相关资源
最近更新 更多