[C/C++] 结构体

主要讲解结构体中的数组和指针

固定缓冲区

#define MAX_LEN 100
#define DATA_LEN 100

typedef struct {
    int length;
    char data[MAX_LEN]; // 固定缓冲区大小,浪费内存
} max_buffer, *max_buffer_ptr;

void base() {
    max_buffer_ptr m_buffer_ptr;
    if ((m_buffer_ptr = (max_buffer_ptr) malloc(sizeof(max_buffer))) != NULL) {
        m_buffer_ptr->length = DATA_LEN;  // 例如实际业务数据缓冲区大小为50
        memcpy(m_buffer_ptr->data, "hello_world", DATA_LEN);
        printf("%s %lu\n", m_buffer_ptr->data, sizeof(m_buffer_ptr->data));
    }
    free(m_buffer_ptr);
}

指针缓冲区

#define MAX_LEN 100
#define DATA_LEN 100

typedef struct {
    int length;
    char *data; // 节约内存,但是结构体和data两次分配的内存是不连续的, 需要分别对其进行管理(申请/释放内存),容易导致遗忘释放内存造成内存泄露
} max_buffer1, *max_buffer_ptr1;

void base_ptr() {
    max_buffer_ptr1 m_buffer_ptr1;
    if ((m_buffer_ptr1 = (max_buffer_ptr1) malloc(sizeof(max_buffer1))) != NULL) {
        m_buffer_ptr1->length = DATA_LEN;
        if ((m_buffer_ptr1->data = (char *) malloc(sizeof(char) * DATA_LEN)) != NULL) {
            memcpy(m_buffer_ptr1->data, "hello_world", DATA_LEN);
            printf("%s %lu\n", m_buffer_ptr1->data, strlen(m_buffer_ptr1->data));
        }
    }
    free(m_buffer_ptr1->data);
    free(m_buffer_ptr1);
}

柔性数组缓冲区

#define MAX_LEN 100
#define DATA_LEN 100

typedef struct {
    int length;
    char data[]; // 柔性数组,地址连续,只需要一次 malloc/free;对结构体格式有要求,必要放在最后,不是唯一成员
} max_buffer2, *max_buffer_ptr2;

void base_soft_array() {
    max_buffer_ptr2 m_buffer_ptr2;
    if ((m_buffer_ptr2 = (max_buffer_ptr2) malloc(sizeof(max_buffer2) + sizeof(char) * DATA_LEN)) != NULL) {
        m_buffer_ptr2->length = DATA_LEN;  // 例如实际业务数据缓冲区大小为50
        memcpy(m_buffer_ptr2->data, "hello_world", DATA_LEN);
        printf("%s %lu\n", m_buffer_ptr2->data, sizeof(m_buffer_ptr->data));
    }
    free(m_buffer_ptr2);
}
posted @ 2023-06-10 23:15  __Helios  阅读(8)  评论(0编辑  收藏  举报