Passing a pointer to a struct and the -> operator in C

chris (2008-10-31 18:23:06)
1467 views
0 replies
Exploring structs, and passing references, here is a very simple example of using the -> operator to access an element within a struct which is referred to by a pointer. in this case, using ptr->age would be equivalent to using (ptr*).age but the -> operator was created to make that simpler.

#include <stdio.h>

struct student{
	int age;
	int year;
};

void display(struct student* ptr);

int main(int argc, char* argv[]){
	struct student p; 
	p.age = 21;
	p.year = 2;

	display(&p);
	return 0;
}

void display(struct student* ptr){
	printf("n%d and %dn",ptr->age, ptr->year);
}


of course this can be compiled and run to give the following output:

secondhalf-lm:junk clacy$ gcc struct.c -o struct && ./struct

21 and 2


christo
comment