Itay Zaguri
Itay Zaguri

Reputation: 45

trying to scanf value in a function to a struct inside a struct with a pointer

just look at the code please , says it all

#include<stdio.h>
#include<string.h>

struct DOB
{
int y,m,d;
}typedef DOB_t;

struct Courses
{
char* NameofCourse;
char* Lec;
int CourseID;

}typedef Course_t;

struct Student
{
char Name[20];
float Grade;
DOB_t dob;
Course_t Courses;

}typedef Student_t;

void addstudent(Student_t* s);
void addDate(DOB_t* dob);
void addCourse(Course_t* c);

main()
{
int opt;
Student_t s;
printf("Please choose one of the options:\n");
printf("<<<<<1.add student>>>>>\n<<<<<2.print student>>>>>\n");
scanf("%d",&opt);
switch(opt)
    case 1:
{
    addstudent(&s);
    break;
}

}

void addstudent(Student_t* s)
{
printf("Enter student's name: ");
scanf("%s",s->Name);
printf("Enter Grade: ");
scanf("%.2f",s->Grade);
printf("Enter DateOfBirth: ");
***addDate(&(s->dob));***
addCourse(&(s->Courses));
}

void addDate(DOB_t* dob)
{
***scanf("%d %d %d", dob->d,dob->m,dob->y);***
}

void addCourse(Course_t* c)
{
printf("Enter Course Name And Lec Name: ");
scanf("%s %s",c->NameofCourse,c->Lec);
printf("Enter Course ID: ");
scanf("%d",c->CourseID);
}

it's not finished yet , but look at the highlighted row - i get an error when i'm triyng to scan values of DateofBirth using pointers into (s->DOB ) to keep the data in the value after function closes. hope you understand my problem.

Upvotes: 0

Views: 1836

Answers (1)

Nishant
Nishant

Reputation: 1665

scanf requires you to pass the address of the memory space you want to store the result in. In your functions, wherever you are passing pointer to the structure,you should use scanf like this.

void addDate(DOB_t* dob)
{
scanf("%d %d %d", &dob->d,&dob->m,&dob->y); //This would read an integer into the address of pointer plus the offset of member into the structure.
}

You have make this change in your code at every place where you are reading values into structure pointer.

Upvotes: 2

Related Questions