为什么会出现“从不兼容类型'void *'“分配给'int *'错误?

Flo*_*Ory 4 c gcc

我在codeacademy上学习c,并且从不兼容的类型“ void *”错误中分配了“ int *”。我的文件是一个.c文件,其中包括stdlib.h。我不理解该错误,似乎更正使用了相同的代码行。

我正在尝试使用malloc创建一个数组。

我试图找到其他主题的答案。看来malloc并不是做到这一点的最佳方法,但我想找到一种使它起作用的方法。

我在Mac上,我使用emacs进行编码和gcc进行编译。

这是我的代码的一部分:

int main(int argc, char *argv[])
{
  char mot_secret[] = "PISCINE";
  int nombre_lettres = strlen(mot_secret);
  int *pnombre_lettres = &nombre_lettres;
  int *decouverte = NULL;
  int compteur = 10;

  decouverte = malloc(nombre_lettres * sizeof(int));
  if (decouverte == NULL)
    {
      exit(0);
    }

Run Code Online (Sandbox Code Playgroud)

这是解决方案:(我尝试翻译一些变量)

int main(int argc, char* argv[])
{
    char lettre = 0;
    char secretword[100] = {0};
    int *lettreTrouvee = NULL; 
    long coupsRestants = 10; // Compteur de coups restants (0 = mort)
    long i = 0;
    long wordSize = 0;

    wordSize = strlen(secretWord);

    lettreTrouvee = malloc(tailleMot * sizeof(int)); // creates a dynamic array of the size of the original)
    if (lettreTrouvee == NULL)
        exit(0);

Run Code Online (Sandbox Code Playgroud)

错误是:

TP.C:17:16: error: assigning to 'int *' from incompatible type 'void *'
  decouverte = malloc(nombre_lettres * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助,对于我在英语上的任何错误,我们深表歉意。

小智 12

您的文件名称似乎是TP.C

在Unix传统中,C源文件被命名为*.c(小写的c),而C ++源文件被命名为*.C(大写的C)。由于*.cppWindows不区分大小写,因此在Windows上使用了替代方法,但是MacOS上的gcc足够像unix一样,它将*.C文件视为C ++。


And*_*nle 8

鉴于此错误消息:

TP.C:17:16: error: assigning to 'int *' from incompatible type 'void *'
  decouverte = malloc(nombre_lettres * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

看来您的文件名为TP.C大写.C文件扩展名使GCC将文件编译为C ++

file.cc
file.cp
file.cxx
file.cpp
file.CPP
file.c++
file.C
Run Code Online (Sandbox Code Playgroud)

必须预处理的C ++源代码。请注意,在“ .cxx”中,最后两个>必须都在字面上是“ x”。同样,“。C”是指文字大写的C。

您需要使用小写字母。重命名文件,使其以.c小写字母结尾c