-
simple linked list
I'm using the following short code to help me understand linked lists (keep things simple at this stage!). The code compiles with the warning -
": warning C4133: "=" : incompatible types - from 'struct RECORD *' to 'struct RECORD *' .
All I am checking with this code is that I can assign the address of the next location in the list to the current record (BTW I know that I have only one record in the list ).
When I run the program it appears to work ok, but that warning is confusing me - can anyone help?
Regards
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define listSize 10
/* global structure definitions */
typedef struct
{
char name[10];
struct RECORD *nextPtr;
} RECORD; /* end structure */
int main(void)
{
/* declare local variables and initialise */
RECORD myRecord = {"abc", NULL};
RECORD *listPtrStart = NULL, *listPtrCurrent = NULL;
/* allocate sufficient memory to store the list */
listPtrStart = (RECORD *) malloc(listSize*sizeof (RECORD));
if(listPtrStart != NULL)
{
listPtrCurrent = listPtrStart;
/* insert a copy of 'myRecord' into the list */
*listPtrCurrent = myRecord;
/* move list pointer to next location and store its value */
listPtrCurrent->nextPtr = listPtrCurrent + 1;
}
else
{
printf("Memory not allocated");
}
return 0; /* indicate successful termination */
}
-
Code:
typedef struct RECORD
-
Hi there. I'm a bit new to the forums but I think the above poster meant that your structure should be declared:
Code:
typedef struct _RECORD
{
char name[10];
struct _RECORD *nextPtr;
} RECORD;
Since you're using the struct you declared within it's own definition.
You also don't need to have a macro for the list's size because linked lists by nature have no maximum size. So you're allocating way too much space with that malloc. I think it would be better to allocate each node (RECORD struct) as you go along and I wrote up an example of what I'm talking about:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct _RECORD
{
char *name;
struct _RECORD *nextPtr;
} RECORD;
int main(void)
{
/* Allocating a new linked list (LL) */
RECORD *myRecord = (RECORD *) malloc( sizeof( RECORD ) );
if (!myRecord) { printf("Memory not allocated\n"); return -1; }
/* Couple of strings to add to LL's later */
char *str1 = "abc";
char *str2 = "def";
/* Setting up the LL's data members */
myRecord->name = str1;
myRecord->nextPtr = NULL;
/* Allocating another LL to add */
RECORD *newRecord = (RECORD *) malloc( sizeof( RECORD ) );
if (!newRecord) { printf("Memory not allocated\n"); return -1; }
newRecord->name = str2;
newRecord->nextPtr = NULL;
/* Now we "link" the first node to the 2nd node */
myRecord->nextPtr = newRecord;
printf("First node's str: %s\n", myRecord->name);
printf("Successor's str: %s\n", myRecord->nextPtr->name);
free(myRecord);
free(newRecord);
return 0;
}
So the output of that code would be:
abc
def
I hope this helps and if anyone sees anything that I did wrong please let me know