About structure pointers

Asked 2 years ago, Updated 2 years ago, 145 views

struct Person {
char name[20];
int age;
char address[100]

};

int main
{ {

struct Person p1;
struct Person *ptr;
ptr = &p1;
} }

Even if there is no third line in int main, the variable ptr in the second line is already

Since I have the memory address of p1, isn't it okay not to have the third line?

pointer struct

2022-09-22 19:22

2 Answers

I think you're confused with the arrangement or other languages.

A structure and a structure pointer are different types of variables.

I've created a simple code to check.

#include <stdio.h>

struct Person {
char name[20];
int age;
char address[100];
};
int main(void)
{
    struct Person p1;
    struct Person *ptr;
    char character;
    int integer;
    ptr = &p1;

    printf("size of p1 : %ld\n",sizeof(p1));
    printf("size of ptr : %ld\n",sizeof(ptr));
    printf("size of char : %ld\n",sizeof(character));
    printf("size of int : %ld\n",sizeof(integer));
} 

If you run the code, you will see the following output.

size of p1 : 124
size of ptr : 8
size of char : 1
size of int : 4

If you look at it, you can see that the size of p1 and ptr variables are different, right?

Because ptr is pointer type, it has a size of 8byte.

On the other hand, p1 will have a size of 124byte, plus 20 chars, 1 int, and 100 chars, to hold the entire structure of the structure. [ (1x20) + (4) + (1x100) = 124byte ]

And then there's going to be a little bit of a different approach to the inside of the structure in the code. For example, if you want to access the age inside the structure, you can approach it in the following ways.

int method1 = p1.age;
int method2 = ptr->age;
int method3 = (&p1)->age;
int method4 = (*ptr).age;

Oh, and next time you ask me questions, please read and write the grammar like Mark It's easier to see^


2022-09-22 19:22

structure Person p1; // Assign memory the size of structure Person to the stack 
structurePerson *ptr; // declare pointer variable of structurePerson type
ptr = &p1; // Place the p1 address in the structure

The third line above is to substitute the memory address of p1 into ptr.


2022-09-22 19:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.