下面是我在课堂上做作业的代码段,但是当我尝试编译它时会弹出:
[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) );
}
答案 0 :(得分:-3)
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;
}
而且,不要忘记释放已用的内存!