I’m a novice C programmer, and I have what is probably a simple question. I’m learning about using pointers to structs currently, and I can’t understand why lines 20 or 22 below work. I understand that scanf() requires you to provide the address of the variable to which you want to assign a value. But since this scanf() placed in the scope of a function which takes a pointer to a struct as an argument, why isn’t “&k->avg” considered a double pointer? If you cascade the values through, isn’t the aforementioned equal to “&&s->avg”?
// Online C compiler to run C program online
#include <stdio.h>
#include <stdint.h>
#include <stdio.h>
struct student {
float avg;
int roll;
};
void read(struct student *);
void display(struct student *);
void main() {
struct student s;
read(&s);
display(&s);
}
void read(struct student *k) {
printf("Enter the average of the student : ");
scanf("%f", &k->avg);
printf("Enter the roll number of the student : ");
scanf("%d", &k->roll);
}
void display(struct student *k) {
printf("Given details are :nRoll Number of the student : %dnAverage mark of the student : %fn", k->roll, k->avg);
}
I tried taking away the “&” but I get a segmentation error when I do that. Leaving the “&” in place, the code works fine.
Robert Fichera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.