将struct传递给函数并在C中修改它

时间:2014-12-09 20:54:47

标签: c pointers struct

所以我有以下代码:

struct list_el{
   int val;
   struct list_el * next;
};

typedef struct list_el item;

...

我在prev中有一个值列表,我希望使用此列表对其进行分析。我的意思是,它是int的列表,因此每个int表示一个令牌。它是一个语法分析器。

所以我想逐步分析它。像这样:

if (program(prev)){
    printf("SINTAX OK.\n");
    system("PAUSE");
    return EXIT_SUCCESS;
}else{
    printf("Error.\n");
    system("PAUSE");
    return EXIT_FAILURE;
}

program

int program(item *list){
   if (list->val == 11) list = list->next;
   else return 0;
   while (list->val == 13) datEst(list);
   if (list->val == 12) list = list->next;
   else return 0;
   if (list == NULL) return 1;
   else return 0;    
}

datEst

int datEst(item *list){
    if(list->val == 13){
        list = list->next;
        return 1;
    }else return 0;
}

所以事情是它在没有使用while (list->val == 13) datEst(list);的情况下正常工作,但是当它必须使用datEst时它会失败。

我认为这是一个深刻的问题,但我不确定。

任何线索或建议?提前谢谢你,抱歉我的英语不好。

3 个答案:

答案 0 :(得分:0)

while (list->val == 13) datEst(list);
如果list->val等于13

将保持无限循环。

您正在修改list中的datEst,但这只是变量的本地副本。它不会更改listprogram指向的内容。

可能的解决方案:

while (list && list->val == 13) list = list->next;

答案 1 :(得分:0)

一个选项是改变

  int datEst(item *list){
    if(list->val == 13){
       list = list->next;
       return 1;
    }else return 0;
  }

  int datEst(item& list){
    if(list.val == 13){
       list = list.next;
       return 1;
    }else return 0;
  }

这会将list转换为通过引用传递的参数,这可能是您想要的。

答案 2 :(得分:0)

c没有引用,但它有指针指针

int datEst(item ** listRef)
{
     item* list = *listRef;  // dereference the first pointer to get a local list

    if(list->val == 13)
    {
        list = list->next;

        *listRef = list;         // store the new list value
        return 1;
    }else return 0;
}

并且需要像这样调用:

while (list != NULL && list->val == 13)
{
    datEst( &list );
}
相关问题