pass pointer to array of structs in c

chris (2008-11-02 21:09:17)
2168 views
0 replies
To pass a pointer to an array of structs in c, it helps to remember that when passing an array to a function, you are effectively passing a pointer to the first element of the array. In this example, I start off using typedef to define a struct datatype called 'student'. The main function then declares an array of 3 students and then populates them with values. Then the display function is called, just passing in the name of the array. The display function prototype specifies that it will accept a pointer to a struct. So what gets passed is a pointer to the first struct (i.e. in the 0th position of the array).

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

typedef struct{
        int age;
        int year;
        char* name;
} student ;

void display( student *p );

int main(int argc, char *argv[]){
        student *p;

        p = malloc(sizeof(student)*3);

        p[0].name = "fred";
        p[0].age = 21;
        p[0].year = 2;
        p[1].name = "barney";
        p[1].age = 23;
        p[1].year = 2;
        p[2].name = "wilma";
        p[2].age = 24;
        p[2].year = 3;

        display(p);

        return 0;
}

void display( student *p){
        printf("\n%s: age: %d, year: %dn",p[0].name,p[0].age,p[0].year);
        printf("\n%s: age: %d, year: %dn",p[1].name,p[1].age,p[1].year);
        printf("\n%s: age: %d, year: %dn",p[2].name,p[2].age,p[2].year);
}

If you compile and run this example, you'll get a print out of all 3 struct contents:

secondhalf-lm:temp clacy$ gcc passstructarray.c -o passstruct && ./passstruct

fred: age: 21, year: 2

barney: age: 23, year: 2

wilma: age: 24, year: 3


christo
comment