代码之家  ›  专栏  ›  技术社区  ›  alex

在C中,malloc()有哪些有用的例子?

  •  14
  • alex  · 技术社区  · 14 年前

    我只是在读 malloc() 在C.

    这个 Wikipedia article 提供了一个 example 但是,它只需要为10个整数的数组分配足够的内存 int array[10] . 不是很有用。

    你什么时候决定用 马尔洛() 为你处理记忆?

    6 回复  |  直到 13 年前
        1
  •  19
  •   Eli Bendersky    14 年前

    malloc

    /* A singly-linked list node, holding data and pointer to next node */
    struct slnode_t
    {
        struct slnode_t* next;
        int data;
    };
    
    typedef struct slnode_t slnode;
    
    /* Allocate a new node with the given data and next pointer */
    slnode* sl_new_node(int data, slnode* next)
    {
        slnode* node = malloc(sizeof *node);
        node->data = data;
        node->next = next;
        return node;
    }
    
    /* Insert the given data at the front of the list specified by a 
    ** pointer to the head node
    */
    void sl_insert_front(slnode** head, int data)
    {
        slnode* node = sl_new_node(data, *head);
        *head = node;
    }
    

    sl_insert_front

        2
  •  4
  •   alex    13 年前

        3
  •  2
  •   rerun    14 年前

    int array[10]

        4
  •  2
  •   Community CDub    8 年前

    Stack and Heap

    int* heapArray = (int*)malloc(10 * sizeof(int));
    int stackArray[10];
    

    free(heapArray)

        5
  •  1
  •   paxdiablo    14 年前

    malloc

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct sNode {
        int payLoad;
        struct sNode *next;
    } tNode;
    
    void stkPush (tNode **stk, int val) {
        tNode *newNode = malloc (sizeof (tNode));
        if (newNode == NULL) return;
        newNode->payLoad = val;
        newNode->next = *stk;
        *stk = newNode;
    }
    
    int stkPop (tNode **stk) {
        tNode *oldNode;
        int val;
        if (*stk == NULL) return 0;
        oldNode = *stk;
        *stk = oldNode->next;
        val = oldNode->payLoad;
        free (oldNode);
        return val;
    }
    
    int main (void) {
        tNode *top = NULL;
        stkPush (&top, 42);
        printf ("%d\n", stkPop (&top));
        return 0;
    }
    

        6
  •  1
  •   Kel    14 年前