#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.
mallocresult to(struct student *), not(struct student).<malloc.h>unless you're using the fancy extra features. The<stdlib.h>header declares the basic memory allocation functions:malloc(),realloc(),calloc()andfree().malloc. In C++ don't use it at all, usenewinstead.free(c)once you've fixed the other problems. Otherwise, you leak memory. It is as well to get into the habit of tracking memory reliably from the start of your career usingmalloc()et al. And be aware thatvalgrindis your friend if it runs on the system you use (and you can always host a VM to be able to run it in the VM if it won't run in your native system).