0.1 内存管理

请写一个程序
这个程序允许用户输入最多20个名字,每个名字最长10个字符
每输入一个名字后换行,输入一个空行表示输入完毕
我们用一个动态分配的数组来存储所有的名字,名字之间用0来分隔

主程序 (不能修改)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

///////////////////////////////////////////////////
// 下面是一个帮助我们使用动态内存分配的库
// 里面包括一个 struct memory 数据来记录正在使用的内存信息
// 和3个工具函数

struct memory
{
    unsigned long length;
    void * ptr;
};
    
struct memory memory_init(unsigned long length) {
    struct memory m;
    m.length = length;
    m.ptr = malloc(length);
    if (m.ptr != NULL)
        memset(m.ptr, 0, length);
    else
        m.length = 0;
    return m;
}

void memory_resize(struct memory * m, unsigned long length) {
    if (length > m->length) {
        m->ptr = realloc(m->ptr, length);
        if (m->ptr == NULL)
            m->length = 0;
        else
            m->length = length;
    }
}

void memory_cleanup(struct memory * m) {
    if (m->ptr != NULL) {
        free(m->ptr);
        m->ptr = NULL;
        m->length = 0;
    }
}

////////////////////
// 下面是测试的工具函数

#include <stdio.h>
#include <string.h>

void print_names(int names_count, char * names_ptr) {
    for (int i = 0; i < names_count; ++ i) {
        printf("%s\n", names_ptr);
        names_ptr = names_ptr + strlen(names_ptr) + 1;
    }
}

#include "source.c"

答案

int get_line(char line[],int len_linmit){
    if(fgets(line,len_linmit,stdin)==NULL) return 0;
    int len=strlen(line);
    while(len>0&&line[len-1]=='\n'){
        line[len-1]=0;
        --len;
    }
    return len;
}

int main() {
    int names_count=0;
    int names_total_length=0;
    struct memory m=memory_init(10);
    for (int i = 0; i < 20; ++ i){
        char tmp[12];
        int len=get_line(tmp,12);
        if(len==0)break;
    
    while(m.length<names_total_length+len+1)
        memory_resize(&m,m.length*2);
    
    strcpy(m.ptr+names_total_length,tmp);
    names_total_length+=len+1;
    names_count ++;
    }
    print_names(names_count,m.ptr);
    memory_cleanup(&m);
}
上一篇: 1.1 (C++) 下一篇: 2020-midterm-8
支持 makedown语法