-
Assignment Errors
Hi, I wrote some code to experiment with a simple linked list. The program runs fine, however the compiler is giving me a warning, "a value of type person cannot be assigned to type LINK."
This makes sense to me, and it would seem that a typecast could fix this, but it doesn't.
I've tried this:
Code:
New->(LINK)next = head ; // set the pointer on the new element to current head value
Objects "New" and "head" are type LINK, and "next" is of type person. I thought I could typecast "next" and temporarily promote it to type LINK.
I get these warnings in two places in red. Any suggestions would be appreciated.
Code:
// 8/31/10
// My simple linked list
#include <stdio.h>
#include <stdlib.h>
struct data
{
char name[10];
struct person *next;
};
typedef struct data PERSON;
typedef PERSON *LINK;
LINK head = NULL; // declare the head pointer
LINK New = NULL;
LINK current = NULL; // save pointer to the first record
int main(void)
{
int i;
char junk;
for( i=0; i<5; i++)
{
New = (LINK)malloc(sizeof(PERSON)); // create an instance of person structure
if( New == NULL)
{
puts("Error allocating memory - terminating....");
return(1);
}
New->next = head ; // set the pointer on the new element to current head value
head = New; // make the head pointer point to the new element
scanf("%s", New -> name); // I haven't learned to use getc() to replace scanf() yet.
junk = getchar(); // clear stdin buffer
}
printf("\n\n");
current = head; // keep copy of last record
for( i=0; i<5; i++)
{
printf("%s\n", current -> name);
current = current -> next;
}
printf("\n\n");
return 0;
}
-
You misnamed your “next” struct pointer type. Surely you meant “struct data”, not “struct person”.
Be careful with casting. It should not, in general, be used to silence warnings. If your compiler's telling you that you have a type mismatch, the cast isn't going to fix the problem; it's only going to silence it. The underlying issue--a type mismatch--is still there.
-
cas, you are absolutely right, I had a typo there. I recall switching my structure name but I forgot to edit the name of the "next" data structure.
As I mentioned, the program ran fine. I have my compiler warnings set on high. It's a good thing I did, because even though the program appeared to run fine, there was still a serious error.
So the next question is... how did this compile at all? It seems like an error should have been issued, not just a warning. I'm off now to add a function to free() memory, and get rid of the scanf() function reading a string.
Thanks a lot cas!
-
Perhaps it worked because LINK and person are the same pointer size. That would mean you could implement the correct intent while being totally wrong. As for why a warning and not an error, it's probably because of the same reason.