简体   繁体   English

malloc显示红线

[英]malloc showing red line

I am using Visual Studio 2012 and using C for programming. 我正在使用Visual Studio 2012并使用C进行编程。 I see that there is no compilation or runtime error(I can give input and output can be displayed) but a red line appear and when I hover on red line it show me an error: error a value of type void * cannot be used to initialize an entity of type "Student*" 我看到没有编译或运行时错误(我可以显示输入和输出),但是出现红线,当我将鼠标悬停在红线上时,它显示错误: 错误类型为void *的值不能用于初始化“Student *”类型的实体

Here is my code: 这是我的代码:

    typedef struct{
            char* firstName;
            char* lastName;
            int day;
            int month;
            int year;

        }STUDENT;

        int numStudents=3;
        int x;
    // Here it show red line, when I hover on it, it show me message
    // 
        STUDENT* students = malloc(numStudents * sizeof *students); // Here it show red line
        for (x = 0; x < numStudents; x++){
            students[x].firstName=(char*)malloc(sizeof(char*));
            scanf("%s",students[x].firstName);
            students[x].lastName=(char*)malloc(sizeof(char*));
            scanf("%s",students[x].lastName);
            scanf("%d",&students[x].day);
            scanf("%d",&students[x].month);
            scanf("%d",&students[x].year);
        }
for (x = 0; x < numStudents; x++)
        printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

Please let me know why it happens so, if there is error then it should not compile or run!!! 请让我知道为什么会这样,如果有错误,那么它不应该编译或运行!

Thank you for help in advance! 提前感谢您的帮助!

You are probably compiling as C++, and in it it is mandatory to cast a void pointer, while in C it isn't. 您可能正在编译为C ++,并且在其中必须强制转换void指针,而在C中它则不是。

Tell Visual Studio to compile as C, or cast the result of malloc. 告诉Visual Studio编译为C,或者转换malloc的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM