3

在打印节点的 id 成员变量时,我得到了这段代码和一个奇怪的行为。

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

struct node
{
    int id;
    int visited;
//    struct node *neighbors_[];
};

struct graph
{
    struct node nodes[26];
    int adjMat[26][26];

};

struct stack_item
{
    struct node node;
    struct stack_item *next_;
};

struct myStack
{
    struct stack_item *anfang_;

};

void initGraph(struct graph *graph_);
void push(struct myStack *stack_, struct node node);

int main()
{

    struct graph graph;
    struct myStack stack;
    char ausgabe[26]="";

    initGraph(&graph);


    //READ DATA
    char line[200];
    int firstTime=1,first;

    first=0;
    push(&stack,graph.nodes[first]);

    printf("ID %i\n",stack.anfang_->node.id);
    printf("ID %i\n",stack.anfang_->node.id);

    //FINISHED DATA READING
     //CALL DFS
    //dfs(graph,stack,ausgabe);
}

void push(struct myStack *stack_, struct node node)
{
    struct stack_item item;
    item.node=node;
    item.next_=stack_->anfang_;

    stack_->anfang_=&item;
}

void initGraph(struct graph *graph_)
{
    int i,j;
    for(i=0; i<26; i++)
    {
        struct node node= {i,0};
        graph_->nodes[i]=node;

        for(j=0; j<26; j++)
        {

            graph_->adjMat[i][j]=0;

        }
    }
}

如果我执行此操作,第一个打印命令会导致“ID 0”,第二个会导致“ID 1980796117”。这个值如何通过打印来改变?请任何人帮助我,我真的不知道!

4

1 回答 1

5
void push(struct myStack *stack_, struct node node)
{
    struct stack_item item;
    item.node=node;
    item.next_=stack_->anfang_;

    /* BAD! */
    stack_->anfang_=&item;
}

item is a local variable which, when the push function returns, goes out of scope. Any existing pointers which refer to this object are now invalid, and dereferencing it results in undefined behavior.

You will need to dynamically allocate item (i.e., malloc) if you need it to persist once the function has returned.

于 2012-11-08T22:58:33.710 回答