J's Study log

[C] Structure Pointer 본문

Computer Language/C

[C] Structure Pointer

정우섭 2020. 2. 8. 20:43

Structure Pointer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#define _CRT_SECURE_NO_WARNINGS    // prevent compilation errors due to security warnings
#include <stdio.h>
#include <string.h>    // a header that have declaration of strcpy()
#include <stdlib.h>    // a header that have declaration of malloc(), free()
 
struct Person {    // definition of function
    char name[20];        // struct member 1
    int age;              // struct member 2
    char address[100];    // struct member 3
};
 
int main()
{
    struct Person *ptr = malloc(sizeof(struct Person));    // declare struct pointer, memory allocation
 
    // access sturcture member with '->' operator and allocate value
    strcpy(ptr->name, "Jung");
    ptr->age = 22;
    strcpy(ptr->address, "Republic of Korea");
 
    // access sturcture member with '->' operator and print value
    printf("Name: %s\n", ptr->name);       // Jung
    printf("Age: %d\n", ptr->age);        // 22
    printf("Address: %s\n", ptr->address);    // Repubic of Korea
 
    free(ptr);    // free memory
 
    return 0;
}
 
 
  • struct struct_name *pointer_name = malloc(sizeof(struct struct_name));

  • pointer_name -> struce_member

Dynamic allocation of sturcture is available.

And you can use '->' operator to access sturcture member.

'Computer Language > C' 카테고리의 다른 글

[C] Pointer  (0) 2020.04.28
[C] Integer  (0) 2019.12.01
[C] Data Type  (0) 2019.12.01
[C] Format specifier  (0) 2019.12.01
[C] Operator Priority  (0) 2019.12.01
Comments