编译时出现奇怪的错误

I am getting a weird error when compiling

本文关键字:错误 编译      更新时间:2023-10-16

下面是我在课堂上布置家庭作业的代码段,但是当我尝试编译它时弹出:

[Error] invalid conversion from 'void*' to 'int*' [-fpermissive]

在指针 1-3 上,选择和两个选项。我仍然是一个新手程序员,我不确定为什么现在会发生这种情况。

#include <stdio.h>
#include <stdlib.h>
int main() 
{
int *pointer1, *pointer2, *pointer3;
int *choice;
char * option;
char * option1;
pointer1 = malloc ( sizeof(int) );
pointer2 = malloc ( sizeof(int) );
pointer3 = malloc ( sizeof(int) );
choice   = malloc ( sizeof(int) );
option = malloc ( sizeof(char) );
option1 = malloc ( sizeof(char) );
}

Malloc 函数将返回一个void*。您需要将其转换为正确的类型,如下所示:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int* pointer1, * pointer2, * pointer3;
int* choice;
char* option;
char* option1;
pointer1 = (int*) malloc(sizeof(int));
pointer2 = (int*) malloc(sizeof(int));
pointer3 = (int*) malloc(sizeof(int));
choice = (int*) malloc(sizeof(int));
option = (char*) malloc(sizeof(char));
option1 = (char*) malloc(sizeof(char));
// Clean up after yourself!!!
free(pointer1);
free(pointer2);
free(pointer3);
free(choice);
free(option);
free(option1);
return 0;
}



而且,不要忘记释放已用内存!