我得到分段错误,而比较struct的成员为0。 令人困惑的部分是比较确实发生了几次,然后是粉碎。
请帮忙。 代码:
Dword addup(void)
{
Symbol *curr=NULL;
Dword ans=0;
plast->next=NULL;
if( (phead==NULL) || (plast==NULL) )/*checks that the global pointer to the head & tail is not null.*/
return 0;
curr=phead;
printf("point 1 in addup()********\n");
for( ; curr!=NULL ; curr=curr->next )
{
if(curr!=NULL)
{
if( ((curr->feature.oper)==0) && ((curr->feature.ext)==0) )/*crash here !*/
{
puts("point 2AA in addup()********");
curr->adess=+IC;
ans++;
}
puts("point 2B in addup()********");
}
if((curr->next)==NULL)
break;
}
if( (curr!=NULL) && (plast!=NULL) )
{
if(curr==plast)/*meaning all the list been searched.*/
return ans;
}
return (-1); }
符号:
typedef struct snode {
char label[MAXLABEL];
Dword adess;
struct
{
unsigned int ext:1;
unsigned int oper:1;
}feature;
struct snode *next;
}Symbol;
感谢大家的帮助!
**首先编辑 - phead是指向列表头部的指针。 plast是指向列表的最后一个节点(Symbol)的指针。 在其他功能中初始化。 plast-> next总是为null。(这是在函数的开头 - 因为我想确定)。
**第二次编辑 - 创建功能 -
void csymbl(Dword addess, char *name, Dword ext, Dword ope ){
tempnode.adess=addess;/*tempnode is a global Symbol,that been used to insert new nodes.*/
strcpy(tempnode.label,name);
tempnode.feature.ext=ext;
tempnode.feature.oper=ope;
tempnode.next=NULL;}
将函数连接到列表的函数:
void addsymbol(Symbol a){
if(phead==NULL)/*if phead point to NULL - meaning this is the first symbol been entered & up now the linked list was empty. */
{
phead=&a;
plast=phead;
}
else if(plast==phead)/*If plast point to phead,than there is only one symbol in the list(up to now).*/
{
plast=&a;
phead->next=plast;
plast->next=NULL;
}
else
{
plast->next=&a;
plast=plast->next;
plast->next=NULL;
}}
答案 0 :(得分:4)
您的addsymbol
功能存在 非常 严重问题,导致 未定义的行为 :
void addsymbol(Symbol a){
if(phead==NULL)/*if phead point to NULL - meaning this is the first symbol been entered & up now the linked list was empty. */
{
phead=&a;
plast=phead;
}
...
}
在上面的代码中,如果phead
为NULL
,则指向 本地 变量a
。
局部变量被称为局部变量,因为它们在它们定义的函数内是局部变量,一旦函数返回局部变量就不再存在。局部变量 lifetime 仅适用于定义它的范围。参数与其他局部变量没有区别。
如果存储指向此类局部变量的指针,则指针将变为无效,当您使用指针时,您将具有未定义的行为。
答案 1 :(得分:3)
您没有为第一个元素
初始化next
void addsymbol(Symbol a){
if(phead==NULL)/*if phead point to NULL - meaning this is the first symbol been entered & up now the linked list was empty. */
{
phead=&a;
plast=phead;
// unless set it can have any value
plast->next = NULL;
}
....
}
此外,你应该将a
作为这样的指针传递:
void addsymbol(Symbol* a){
if(phead==NULL)/*if phead point to NULL - meaning this is the first symbol been entered & up now the linked list was empty. */
{
phead=a; // Note this changed - no & operator
正如评论中已经提到的,这里也存在一个问题:
Dword addup(void)
{
Symbol *curr=NULL;
Dword ans=0;
// plast->next=NULL; Don't do it here.... plast may be NULL
if( (phead==NULL) || (plast==NULL) )/*checks that the global pointer to the head & tail is not null.*/
return 0;
plast->next=NULL; // If you really want that code, do it here
最后我想知道你是否真的想要这个:
curr->adess=+IC;
或者
curr->adess+=IC;