I am trying to do this assignment. I am not understanding how can I allocate mem
ID: 3743041 • Letter: I
Question
I am trying to do this assignment. I am not understanding how can I allocate memory to a structure using double pointer. Please help.
#include <stdio.h>
#include <stdlib.h>
typedef struct Contents{
char name[10];
} Contents;
typedef struct Emp{
int id;
char name[10];
int numOfContents;
Contents* contents;
} Emp;
void display(Emp*);
void printValues(Emp*);
int main(){
Emp e;
display(&e);
printValues(&e);
return 0;
}
void display(Emp *e){
Emp** eptr;
eptr = (Emp**) calloc(1, sizeof(Emp**));
printf("Enter id: ");
scanf("%d", eptr->id);
printf("Enter name: ");
scanf("%s", eptr->name);
printf("Enter number: ");
scanf("%d", eptr->numOfContents);
eptr->contents = (Contents*) calloc(eptr-> numOfContents, sizeof(Contents));
for(int i = 0; i < e -> numOfContents; i++){
printf("Enter name of Content: ");
scanf("%s", e->contents->name);
}
return;
}
void printValues(Emp* e){
printf("% ", e->id);
printf("%s ", e->name);
}
Explanation / Answer
hi pease look at the below modified source code and wait i will provide you the screenshot
#include <stdio.h>
#include <stdlib.h>
typedef struct Contents
{
char name[10];
} Contents;
typedef struct Emp
{
int id;
char name[10];
int numOfContents;
Contents* contents;
} Emp;
void display(Emp*);
void printValues(Emp*);
int main()
{
Emp e;
display(&e);
printValues(&e);
return 0;
}
void display(Emp *e)
{
Emp** eptr;
e=(Emp*)malloc(sizeof(Emp*));
printf("Enter id: ");
scanf("%d", &e->id);
printf("Enter name: ");
scanf("%s", e->name);
printf("Enter number: ");
scanf("%d", &e->numOfContents);
*eptr=e;
e->contents=(Contents*)malloc(sizeof(Contents));
for(int i = 0; i < e -> numOfContents; i++)
{
printf("Enter name of Content: ");
scanf("%s", e->contents->name);
}
return;
}
void printValues(Emp* e)
{
printf("% ", e->id);
printf("%s ", e->name);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.