Home > Software design >  I keep getting an error when working with pointers in C
I keep getting an error when working with pointers in C

Time:11-19

I'm writing a program in C which has a container (linear linked list) which contains char arrays as its data. I'm required to write a function firstItem(container* containerADT) which returns the the struct variable top. I've tried writing the firstItem function many times in many different ways and I keep getting the same error. My struct definitions, functions, and error message are below:

Container and Node structs:

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

typedef struct container
{
    struct node *top;
}container;

firstItem function:

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

testing function

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  ;
}

error message:

enter image description here

Please note that I was asked to test the firstItem() function so I can't just access the container's top variable and that a Makefile was used to compile main.c, container.c, and container.h

CodePudding user response:

The problem is that you have named the variable the same name as the function. The variable then 'hides' the definition of the function in the local scope.

node* firstItem = firstItem(container1);

Rename the variable to use another name:

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