代码之家  ›  专栏  ›  技术社区  ›  Ky James

在使用C中的指针时,我总是出错

  •  0
  • Ky James  · 技术社区  · 2 年前

    我正在用C语言编写一个程序,它有一个容器(线性链表),其中包含字符数组作为数据。我需要编写一个函数firstItem(container*containerADT),它返回结构变量top。我已经尝试用许多不同的方式多次编写firstItem函数,但总是出现同样的错误。我的结构定义、函数和错误消息如下:

    容器和节点结构:

    typedef struct node
    {
        char* data;
        struct node *next;
    }node;
    
    typedef struct container
    {
        struct node *top;
    }container;
    

    firstItem函数:

    node* firstItem(container* containerADT)
    {
        // returns the top of the passed container
        return containerADT->top;
     }
    

    测试功能

    printf("\nTesting firstItem() on a non-empty container:");
    node *firstItem;
    firstItem = firstItem(container1);
    numTestsCompleted++;
    if (firstItem != NULL && strcmp(firstItem->data, "item 1") == 0)
    {
        printf("\n\tSUCCESS! firstItem() returned the first item in the container.\n");
    }
    else
    {
        printf("\n\tFailed. firstItem() did not return the first item in the container.\n");
        numTestsFailed++;
    }
    

    错误消息:

    enter image description here

    请注意,我被要求测试firstItem()函数,这样我就不能只访问容器的顶部变量,并且Makefile被用来编译main.c、container.c和container。h

    1 回复  |  直到 2 年前
        1
  •  4
  •   robthebloke    2 年前

    问题是您将变量命名为与函数相同的名称。然后,变量在本地作用域中“隐藏”函数的定义。

    node* firstItem = firstItem(container1);
    

    重命名变量以使用其他名称:

    node *first_item = firstItem(container1);
    if (first_item != NULL && strcmp(first_item->data, "item 1") == 0) {
    }