在 C++ 中从 void* 到 struct* 的无效转换

invalid conversion from void* to strcut* in c++

当我尝试使用 calloc 进行连续内存分配时,它给我类似这样的错误。 在 c++

中从 void* 到 slotstruct(*)[100][1500] 的无效转换

这是我的代码:

typedef struct
 {
   int id;
   bool used;
 }slotstruct;
 int main(){
       slotstruct ( *slot1 )[100][1500];
       slot1 = calloc( 1, 3 * sizeof( *slot1 ) );
      for(i=0;i<3;i++){
         for(j=0;j<100;j++){
            for(k=0;k<1500;k++){
                  cout << "Addresses are : "<<slot1[i][j][k];
           }
      }
    }
 } 

仅针对您的要求:您应该在 C++ 程序中显式执行从 void* 到其他类型的类型转换。

您应该考虑改用 newdelete

C 语言允许 void* 隐式转换(不强制转换)到任何其他对象指针类型。在 C++ 中情况并非如此。您的选择是:

  • 不要使用 C++ 编译器编译 C 代码(最简单)。
  • 执行正确的转换以避免错误(不明智的是,转换,尤其是对于初学者,通常用于隐藏问题而不是解决 他们。不幸的是,为此目的滥用它们并不少见。但是,"solve" 你的问题在这里)。
  • 使用 new[]delete[] 进行序列分配。不需要强制转换,如果您的数据类型变得非常重要,它仍然可以工作。
  • 根本不要使用手动内存分配,而是选择 RAII 方法。

其中第一个很明显,其余的如下所示


使用强制转换

在这种情况下可以正常工作,不会产生不良影响,因为您的 slotstruct 类型很简单:

slot1 = (slotstruct (*)[100][1500])calloc( 1, 3 * sizeof( *slot1 ) ); // allocates
free(slot1); // destroys

使用 new[](和 delete[]

无需强制转换:

slot1 = new slotstruct[3][100][1500]; // allocates..
delete [] slot1; //.. destroys

C++ 替代方案使用 RAII

一个更合适的 C++ RAII 方法看起来像这样:

#include <iostream>
#include <array>
#include <vector>

struct slotstruct
{
    int id;
    bool used;
};

int main()
{
    std::vector<std::array<std::array<slotstruct,1500>, 100>> slots(3);

    for (auto const& x : slots)
        for (auto const& y : x)
            for (auto const& z : y)
                std::cout <<"Address is : " << static_cast<const void*>(&z) << '\n';
}

输出(变化)

Address is : 0x100200000
Address is : 0x100200008
Address is : 0x100200010
Address is : 0x100200018
Address is : 0x100200020
...
Address is : 0x10056ee60
Address is : 0x10056ee68
Address is : 0x10056ee70
Address is : 0x10056ee78