Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I keep getting an error when working with pointers in C

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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) {
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading