Reputation: 33
I want to delete the first node and return the value of the deleted node. But I an getting this warning:
warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
example=(**example).next;
So, my code does not work. Can anyone help me to fix this? Thanks.
struct myStruct {
int data;
struct myStruct next;
}
int deleteNode(struct myStruct **example) {
struct myStruct *temporary;
if (temporary == NULL) {
emptyNode(temporary); // this function only returns NULL
}
temporary = *example;
example = (**example).next;
free(temporary);
return (**example).data;
}
Upvotes: 0
Views: 39
Reputation: 310950
This structure declaration contains at least two typos.
struct myStruct
{
int data;
struct myStruct next;
}
The first one is that there is no semicolon after the closing brace. And the second one is that the data member next must have pointer type.
It seems you mean
struct myStruct
{
int data;
struct myStruct *next;
};
As for the error message then in this assignment
example=(**example).next;
the left side hand operand has the type struct myStruct **
while the right hand side operand has the type struct myStruct *
and these pointer types are not compatible. So the compiler issues an error.
Nevertheless the function in any case is invalid because you are using uninitialized variables like
struct myStruct *temporary;
if(temporary==NULL)
//...
The function interface is bad.because it is unclear what the function returns in case when it is called for an empty list.
The function can be declared and defined the following way.
int deleteNode( struct myStruct **example, int *data )
{
int success = *example != NULL;
if ( success )
{
struct myStruct *temporary = *example;
*example = ( *example )->next;
*data = temporary->data;
free( temporary );
}
return success;
}
And it can be called as it is shown below
#include <stdio.h>
#include <stdlib.h>
struct myStruct
{
int data;
struct myStruct *next;
};
int deleteNode( struct myStruct **example, int *data )
{
int success = *example != NULL;
if ( success )
{
struct myStruct *temporary = *example;
*example = ( *example )->next;
*data = temporary->data;
free( temporary );
}
return success;
}
int main(void)
{
struct myStruct *head = 0;
// fill the list
int data;
if ( deleteNode( &head, &data ) )
{
printf( "The deleted value is %d\n", data );
}
else
{
puts( "The list is empty." );
}
return 0;
}
Upvotes: 1