簡體   English   中英

從“ void *”類型強制轉換為“ int *”類型

[英]invalid cast from type 'void*' to type 'int*'

補充2 :更改為static ,它可以在Windows上的ubuntu上的bash中的gcc 4.8.4(ubuntu 4.8.4-2ubuntu1〜14 .04.3)中正常工作。 但是在使用gcc 4.9.2(tdm-1)的Windows10中它不能工作。 我將編譯器更改為cygwin,它具有gcc 4.9.2,而不是tdm-1版本。 很奇怪,它有效! 所以我認為編譯器也有一些錯誤!

1 :很抱歉我發現我的編譯器不是gcc還是g ++,我是程序領域的新手,請原諒。 我用.c來構建,但是它有一些我無法處理的內存泄漏錯誤。 因此,我更改為.cpp進行構建,並且出現了這些錯誤。 這就是我的情況。

Windows 10的橢圓GCC 4.8.4 我使用C語言。

elipse給我一個錯誤: 從類型'void *'強制轉換為類型'int *'[-fpermissive]

橢圓提示這些行有錯誤

FullList = malloc(N * sizeof(int));
l = malloc(N * sizeof(int));

我不知道該如何糾正。 任何線索將不勝感激!

這是涉及這句話的功能。

#define ALLCHK(x) if (x == NULL) {printf ("allocation error\n"); assert(x);}
void Generate_Permutation(int N, int *p)
/* generate permutation of length N in p */
/* p is zero based, but the permutation is not */
{
  int i,j;         /* to loop */
  int lspot;         /* offset in l */
  int *FullList;       /* unpermuted */
  int *l;          /* left to be used */

  FullList = malloc(N * sizeof(int));
  ALLCHK(FullList)
  for (i=0; i<N; i++) *(FullList+i) = i+1;
  l = malloc(N * sizeof(int));
  ALLCHK(l)

  memcpy(l, FullList, sizeof(int)*N);
  for (i=0; i < N; i++) {
    lspot = (int)(URan(&seed) * (N - i));
    *(p+i) = *(l+lspot);
    for (j=lspot; j<N-i; j++) *(l+j) = *(l+j+1);
  }
  free(l); free(FullList);
}

在C ++中, void*不能隱式轉換為int* 您需要顯式轉換malloc的結果:

fullList = static_cast<int*>(malloc(N * sizeof(int)));
l = static_cast<int*>(malloc(N * sizeof(int)));

由於您使用的是C ++,因此最好使用new運算符:

fullList = new int[N];
l = new int[N];

// some code...

delete[] fullList;
delete[] l;

在進行此操作時,您可以使用唯一的指針:

std::unique_ptr<int[]> fullList = new int[N];
std::unique_ptr<int[]> l = new int[N];

// no delete at the end of the scope

但更簡單的是,只需使用向量:

std::vector<int> fullList(N);
std::vector<int> l(N);

對我來說,似乎您正在將C代碼片段移植到C ++(包括在C ++項目中?)。

將此答案視為解決問題的快速解決方案,而不是最佳解決方案。

在C ++中使用malloc / free時,必須將malloc返回的void*指針轉換為所需的指針類型:

FullList = static_cast<int*>(malloc(N * sizeof(int)));
l = static_cast<int*>(malloc(N * sizeof(int)));

這樣做的原因(當簡單地復制C代碼時)是因為在C中,這些強制轉換可以隱式執行。

其他選擇是使用C編譯器編譯該文件,對於該文件,只需將文件重命名為.c而不是.cpp擴展名就足夠了。 然后,g ++(C ++編譯器)將自動使用gcc(C編譯器)來編譯代碼。

同樣,另一個選擇是使用new / delete而不是malloc / free將其重寫為“真實的” C ++代碼,但是同樣可以將其重寫為使用現代內存管理(例如std :: vectors等)。

在C語言中,您不必強制轉換(void *)malloc的結果。 在C ++中,除非您強制轉換,否則編譯器會哭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM