首页 > 解决方案 > C 编程使用 malloc 和赋值

问题描述

我是 C 编程新手。我正在为一个需要我使用 malloc 的学校项目工作。

我的问题是:在分配指针之前还是之后调用 malloc 更好

例如:

    struct Node{
       int value; 
       struct Node* next; 
    }

    int main(int argc, char** argv){

        struct Node* mylist = //something

        //which of the following is the correct way to do this? 
        struct Node* node = mylist; 
        node = (struct Node*) malloc(1 * sizeof(struct Node)); 

        //or

        struct Node* node = (struct Node*) malloc(1 * sizeof(struct Node));
        node = mylist;
    }

标签: c

解决方案


你想要这样的东西:

struct Node{
   int value; 
   struct Node* next; 
}

int main(int argc, char** argv){

    struct Node* mylist;  // declare the mylist pointer, it points nowhere right now

    mylist = malloc(1 * sizeof *mylist);   // roughly the same as "1 * sizeof(struct Node)"
                                           // now mylist points to a memory region of 
                                           // size (1 * sizeof(struct Node))
    // do something
    mylist->value = 1234;
    .....

    // once you're done 
    free(mylist); 
    // now mylist points nowhere again
}

我建议您阅读 C 教科书中有关指针和动态内存分配的章节。


推荐阅读