2012-12-04 73 views
0

我必须检查s1和s2的顶部卡。 s1是一堆卡片,s2也是。该stack_top功能我已经有了,如下:我比较哪种数据类型?

/* Retrive data from the top of the stack */ 
node_data stack_top(stack *s){ 
    if(!stack_empty(s)){  /* If the stack is not empty */ 
    return (s->top->data); /* Return the data */ 
    } 
    else{    /* Otherwise there is an error */ 
    cardlist_error("stack_top called on empty stack"); 
    } 
} 

while (strcmp (stack_top(s1), stack_top(s2)) ==0) 
//then do the following.. 

,但我得到了segmentation fault,我应该如何对它们进行比较2?

+2

如果堆栈为空,你真的应该从你的函数中返回一些东西。如果你的函数说要返回一些东西,你应该返回一些东西**无论发生什么** – mathematician1975

+0

你需要比较'stack_top'返回的'node_data'的内容。 (你没有包含'node_data'的定义,所以很难确切地说你需要比较的东西;你显示的只是'stack_top'返回's-> top-> data',没有指出什么' data'不是'node_data'。)什么决定它们是否相等? –

回答

1

如果您想检查两个stack指针是否指向同一个实例,请检查它们的地址是否匹配s1 == s2

如果您想检查两个指针​​是否都保存相同的数据,并且结构中只有非指针成员,您可以检查memcmp(s1, s2, sizeof(*s1)) == 0

如果您想检查两个指针​​都保存相同的数据,并且结构中有指针(例如字符串),您可能需要编写一个函数,它通过比较每个成员轮流比较两个实例。