简体   繁体   中英

How to allocate memory to struct pointer using malloc.h header?

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

struct student
{
    char name[25];
    int age;
};

int main()
{
    struct student *c;

    *c =(struct student)malloc(sizeof(struct student));
    return 0;
}

What is the wrong with this code? I tried times by alternating this code to allocate memory to struct pointer. But this error comes when compiling:

testp.c:15:43: error: conversion to non-scalar type requested
  *c =(struct student)malloc(sizeof(struct student));
                                           ^

I'm using mingw32 gcc compiler.

What is the wrong with this code?

Ans: First of all you change that "is" to "are", there are two major problems, atleast. Let me elaborate.

  • Point 1. You allocate memory to the pointer , not to the value of pointer . FWIW, using *c (ie, de-referencing the pointer without memory allocation) is invalid and will result in undefined behaviour .

  • Point 2. Please do not cast the return value of malloc() and family in C. The cast you used is absolutely wrong and proves the authenticity of the first sentence.

To solve the issues, change

*c =(struct student)malloc(sizeof(struct student));

to

c = malloc(sizeof(struct student));

or, for better,

c = malloc(sizeof*c);   //yes, this is not a multiplication
                        //and sizeof is not a function, it's an operator

Also, please note , to make use of malloc() and family , you don't need the malloc.h header file. These functions are prototyped in stdlib.h .


EDIT:

Suggestions:

  1. Check for success of malloc() before using the returned pointer.
  2. Always free() the memory once the usage is over.
  3. The recommended signature of main() is int main(void) .

This worked (on C and C++).
Since you originally included both tags.

change

*c =(struct student)malloc(sizeof(struct student));

to

c =(struct student*) malloc(sizeof(struct student));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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