selva
selva

Reputation: 97

Pointer in nested structure

How do we use the pointers in nested structure?

I created two structure in the code given below, how can I access the elements of st_no? Explain about nested structure thoroughly .

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

typedef struct
{
   char st_no[22];
   int no;
}address;

typedef struct
{
  char name[15];
  int mark;
  address addr;
}student;

int main (void)
{
 student *selva;

strcpy(selva->name, "ajay");
strcpy(selva->addr.st_no,"3rd st");
printf("%s",selva->name);

 return 0;
}

Upvotes: 0

Views: 1766

Answers (2)

Dayal rai
Dayal rai

Reputation: 6606

Use it like below

student *selva;
selva = malloc(sizeof(student));
strcpy(selva->name, "ajay");
strcpy(selva->addr.st_no,"3rd st");

Upvotes: 0

sedavidw
sedavidw

Reputation: 11691

You only have a pointer to a student, not an actual student. To allocate dynamically you need:

student * selva = malloc(sizeof(student))  // be sure to free this later

Then you can do:

strcpy(selva->addr.st_no, "3rd st")

Or if you don't need to do it dynamically, you can create the variable on the stack like so:

student selva

Then to copy into st_no you can:

strcpy(selva.addr.st_no, "3rd st")

Upvotes: 3

Related Questions