C:返回指向结构的指针的函数,只适用于malloc,为什么?

C:返回指向结构的指针的函数,只适用于malloc,为什么?,c,pointers,struct,C,Pointers,Struct,很明显,我是C语言的初学者, 我认为函数initA和initB是可以互换的, 因为它们都返回指向List类型的对象的指针,所以需要自定义结构 但只有initA产生预期的输出 initA和initB有何不同 List *initA() { List *list = malloc(sizeof(*list)); Element *element = malloc(sizeof(*element)); element->number = 0; element-

很明显,我是C语言的初学者, 我认为函数initA和initB是可以互换的, 因为它们都返回指向List类型的对象的指针,所以需要自定义结构 但只有initA产生预期的输出

initA和initB有何不同

List *initA() {

    List *list = malloc(sizeof(*list));
    Element *element = malloc(sizeof(*element));

    element->number = 0;
    element->next = NULL;
    list->first = element;


    return list;
}


List *initB() {
    Element _el = {.number=0, .next=NULL};
    Element *el = &_el;
    List _list = {.first=el};
    List *list = &_list;
    return list;
}
以下是完整的源代码,出于教学方面的原因,试图在这里重现链表的第一步

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


typedef struct Element Element;
struct Element {
    int number;
    Element *next;
};


typedef struct List List;
struct List {
    Element *first;
};




List *initA() {

    List *list = malloc(sizeof(*list));
    Element *element = malloc(sizeof(*element));

    element->number = 0;
    element->next = NULL;
    list->first = element;


    return list;
}

List *initB() {
    Element _el = {.number=0, .next=NULL};
    Element *el = &_el;
    List _list = {.first=el};
    List *list = &_list;
    return list;
}




void printList(List *list){

    Element *el = list->first;
    while (NULL != el) {
        printf("number: %d, next: %p\n", el->number, el->next);
        el = el->next;
    }

}

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

    /**
     * output:  
     * number: 0, next: 0x0
     */
//    List *list = initA();

    /**
     * output:      
     * number: 1344951776, next: 0x7fff502a55d0
     * number: 1344951776, next: 0x29502a55e0
     */
    List *list = initB();
    printList(list);

    return 0;

}

initB返回指向区域设置变量的指针,该变量的作用域仅限于initB。当您退出该函数时,位于该地址的内存可能发生任何情况。因此,这是未定义的行为

不同之处在于initB返回指向未定义行为的局部变量的指针。这件事有很多重复……哦,是的,现在我开始明白了。谢谢。