how to make a struct pointer in c code example

Example 1: return pointer to struct in C

typedef struct {
  char name[20];
  int age;
} Info;

Info* GetData() {
  Info *info;

  info = (Info *) malloc( sizeof(Info) );
  scanf("%s", info.name);
  scanf("%d", &info.age);

  return info;
}

Example 2: how to assign struct address to the pointer

#include

struct dog
{
    char name[10];
    char breed[10];
    int age;
    char color[10];
};

int main()
{
    struct dog my_dog = {"tyke", "Bulldog", 5, "white"};
    struct dog *ptr_dog;
    ptr_dog = &my_dog;

    printf("Dog's name: %s\n", ptr_dog->name);
    printf("Dog's breed: %s\n", ptr_dog->breed);
    printf("Dog's age: %d\n", ptr_dog->age);
    printf("Dog's color: %s\n", ptr_dog->color);

    // changing the name of dog from tyke to jack
    strcpy(ptr_dog->name, "jack");

    // increasing age of dog by 1 year
    ptr_dog->age++;

    printf("Dog's new name is: %s\n", ptr_dog->name);
    printf("Dog's age is: %d\n", ptr_dog->age);

    // signal to operating system program ran fine
    return 0;
}

Example 3: pointer inside structure in c

#include

struct Student
{
   int  *ptr;  //Stores address of integer Variable 
   char *name; //Stores address of Character String
}s1;

int main() 
{

int roll = 20;
s1.ptr   = &roll;
s1.name  = "Pritesh";

printf("\nRoll Number of Student : %d",*s1.ptr);
printf("\nName of Student        : %s",s1.name);

return(0);
}

Tags:

Misc Example