How to allocate and deallocate heap memory for 2D array?

前端 未结 6 1283
一向
一向 2020-12-06 01:04

I\'m used to PHP, but I\'m starting to learn C. I\'m trying to create a program that reads a file line by line and stores each line to an array.

So far I have a prog

6条回答
  •  感动是毒
    2020-12-06 01:54

    Instead of an array here, you could also use a linked list, The code is simpler, but the allocation is more frequent and may suffer from fragmentation.

    As long as you don't plan to do much random access (Which is O(n) here), iteration is about as simple as a regular array.

    typedef struct Line Line;
    struct Line{
        char text[LINE_MAX];
        Line *next;
    };
    
    Line *mkline()
    {
        Line *l = malloc(sizeof(Line));
        if(!l)
           error();
        return l;
    }
    
    main()
    {
        Line *lines = mkline();
        Line *lp = lines;
        while(fgets(lp->text, sizeof lp->text, stdin)!=NULL){
             lp->next = mkline();
             lp = lp->next;
        }
        lp->next = NULL;
    }
    

提交回复
热议问题