[习题16]struct 和 指向struct的指针 : struct Person *who = malloc(sizeof(struct Person));

使用教材

《“笨办法” 学C语言(Learn C The Hard Way)》
https://www.jianshu.com/p/b0631208a794

ex6.c

#include 
#include 
#include 
#include 

struct Person {
    char *name;
    int age;
    int height;
    int weight;
};

struct  Person *Person_create(char *name, int age, int height, int weight)
{
    struct Person *who = malloc(sizeof(struct Person));
    assert(who != NULL);

    who->name = strdup(name);
    who->age = age;
    who->height = height;
    who->weight = weight;

    return who;
}

void Person_destroy(struct Person *who) 
{
    assert(who != NULL);

    free(who->name);
    free(who);
}

void Person_print(struct Person *who) 
{
    printf("Name: %s\n", who->name);
    printf("\tAge: %d\n", who->age);
    printf("\tHeight: %d\n", who->height);
    printf("\tWeight: %d\n", who->weight);
}

int main(int argc, char *argv[]) 
{
    // make two people structures
    struct Person *joe = Person_create("Joe Alex", 32, 64, 140);

    struct Person *frank = Person_create("Frank Blank", 20, 72, 180);

    // print them out and where they are in memory
    printf("Joe is at memory location %p:\n", joe);
    Person_print(joe);

    printf("Frank is at memory location %p:\n", frank);
    Person_print(frank);

    // make everyone age 20 years and print them again
    joe->age += 20;
    joe->height -= 2;
    joe->weight += 40;
    Person_print(joe);

    frank->age += 20;
    frank->height -= 20;
    Person_print(frank);

    //destory them both so we clean up
    Person_destroy(joe);
    Person_destroy(frank);

    return 0;
}

Makefile

CC=clang
CFLAGS=-Wall -g

clean:
    rm -f ex16

run

anno@anno-m:~/Documents/mycode/ex16$ make ex16
clang -Wall -g    ex16.c   -o ex16
anno@anno-m:~/Documents/mycode/ex16$ ./ex16
Joe is at memory location 0x23e0010:
Name: Joe Alex
    Age: 32
    Height: 64
    Weight: 140
Frank is at memory location 0x23e0050:
Name: Frank Blank
    Age: 20
    Height: 72
    Weight: 180
Name: Joe Alex
    Age: 52
    Height: 62
    Weight: 180
Name: Frank Blank
    Age: 40
    Height: 52
    Weight: 180

note

  • 结构体是一些数据类型(变量)的集合,存储在一整块内存中;

#include

void *malloc(size_t size);
void free(void *ptr);
  • malloc,进行内存分配(memory allocate),让操作系统给我一块原始内存;
  • free,归还用mallocstrdup获取的内存,否则会造成内存泄露

#include

  • strdup,创建一个新的字符串,制作一个name的副本,strdupmalloc差不多,它还会将原始字符串复制到它创建的内存中;
  • char *strdup(const char *s);

#include

  • assert,确保从malloc得到了一块有效的内存,使用了一个特殊常量NULL

ptr->elem

  • struct Person *joe = Person_create("Joe Alex", 32, 64, 140);
  • joe->age += 20;
  • 指针 -> 结构体的元素 :访问结构体里的元素;

检测动态内存分配

[Valgrind]检测动态分配的内存DAM(Dynamically Allocated Memory)
https://www.jianshu.com/p/e3bb358ccc3f

你可能感兴趣的:([习题16]struct 和 指向struct的指针 : struct Person *who = malloc(sizeof(struct Person));)