pointer to structure in c code example
Example 1: how to assign struct address to the pointer
#include<stdio.h>
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);
strcpy(ptr_dog->name, "jack");
ptr_dog->age++;
printf("Dog's new name is: %s\n", ptr_dog->name);
printf("Dog's age is: %d\n", ptr_dog->age);
return 0;
}
Example 2: structs in c
#include <stdio.h>
#include <stdlib.h>
struct book{
char name[50];
char author[50];
char ISBN[11];
};
int main(){
struct book book1;
strcpy(book1.name, "james and the giant tatti");
strcpy(book1.author, "Krishan Grewal");
strcpy(book1.ISBN, "12345678987");
printf("book name: %s\n", book1.name);
printf("book author: %s\n", book1.author);
printf("book ISBN: %s\n", book1.ISBN);
return 0;
}
Example 3: how to use a pointer as a parameter in c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void add(int* a, int* b, int* c)
{
*c = *a + *b;
}
int main()
{
int a, b, c;
a = 3;
b = 5;
add(&a, &b, &c);
printf("%d", c);
}
Example 4: pointer inside structure in c
#include<stdio.h>
struct Student
{
int *ptr;
char *name;
}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);
}