Answer (see below): When accessing a struct with a pointer, one needs to use the arrow operator "myStruct->structVariable" which is the equivalent to "(*myStruct).structVariable". When accessing the struct directly one uses "myStruct.structVariable".
I'm pretty new to C and pointers and am trying to do the following: I'd like to access an array of structs which is part of another struct. The struct is a pointer which gets passed to a function, in which i would like to access it.
Student has an array of structs which 10 Lectures (also a struct). To simplify the process of adding lectures to a student, i would like to be able to call the function "addLectureToStudent()" and passing the necessary arguments and assign the values to the array of lectures.
typedef struct Lectures {
char name[20];
} Lecture;
typedef struct Students {
char name[20];
Lecture lectures[10];
} Student;
void addLectureToStudent(Student * stud, int position, char lecture_name[20]){
strcpy(stud->lectures[position]->name, lecture_name); //This line doesn't work as expected
}
int main(void) {
Student markus;
strcpy(markus.name, "Markus");
markus.matrikelnummer = 12089548;
addLectureToStudent(&markus, 0, "Programming");
}
My problem is, that when wanting to access strcpy(stud->lectures[postition]->name, lecture_name)
it tells me that stud should be a pointer but isn't (thats the best translation i can come up with. It is originally in german..). How do i access the array of lectures properly in this case?
stud->lectures[position]
is Lecture
, so you should use .
, not ->
, to access that.
strcpy(stud->lectures[position].name, lecture_name);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments