C Strut and Pointer

1.What is Strut in C?
-Struct in C is used to visualize the object with attributes.
-For example, we can have the object “dog” with attributes as name, breed, age, color. Then, we should declare the dog in struct type as:


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

-Here, we declare a struct name dog with attributes.

2.How to use a Struct
-To use a struct, we need to instance a struct. The meaning is just like the instance of a class to have an object.
-For example:
struct dog my_dog;//instance without initial values
struct dog my_dog = {“tyke”, “Bulldog”, 5, “white”};//instance with initial values
-We cab read the example above as “create an object my_dog in the type of struct dog”.

3.How to Access Attributes of Struct Object?
-To simple access Struct Object, we use the -> Operation, for example:


struct dog my_dog = {"tyke", "Bulldog", 5, "white"};//(1)
struct dog *ptr_dog;//(2)
ptr_dog = &my_dog;//(3)

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);


-Look at the (1)(2), we will see that, a struct will be initialize with a pointer with same datatype
-Look at the (3), we will see that the pointer will point to the struct to iterate for attributes of the struct object
-Then, we can access the attribute values by the syntax pointer->attr as "ptr_dog->name"

4.Full example of Struct and 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);

    // 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;
}

Click here for more information on Pointer...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.