mkahihu mkahihu - 4 years ago 127
C Question

Assignment from incompatible pointer type and derefrencing pointer to incomplete type

I am trying to get chars and the number of each and put them into a linked list. As the title states i keep getting a warning about incompatible pointer types and an error about dereferencing incomplete type. I think the last one i said is because start is null but I dont see why when i assigned it to temp. Help please.

/* Author: Miller Kahihu
Date: 2017-02-01
Program getChars.c
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct linkedList
{
struct Element* start;
int size;
} LinkedList;

typedef struct element
{
char key;
int value;
struct Element* next;
} Element;

int main(int argc, char** argv)
{
LinkedList* list = malloc(sizeof(LinkedList));
list->start = NULL;
list->size = 0;

char* fileName = NULL;
if(argc > 1)
{
fileName = argv[1];
}
else
{
exit(1);
}
FILE* fpIn = fopen(fileName, "r");
if(!fpIn)
{
fprintf(stderr, "file %s could not be opened\n", fileName);
exit(1);
}
int c;
Element* temp = (Element*) malloc(sizeof(Element));
while((c=fgetc(fpIn)) !=EOF)
{
if(list->start == NULL)
{
temp->key = (char) c;
temp->value = 1;
temp->next = NULL;
list->start = temp;
printf("%c kappa\n", list->start->key);
}
else
{
printf("%c\n", (char) c);
}
}
//free(temp);
return 0;
}


Here is the full error message

getChars.c: In function ‘main’:
getChars.c:51:25: warning: assignment from incompatible pointer type [enabled by default]
list->start = temp;
^
getChars.c:52:45: error: dereferencing pointer to incomplete type
printf("%c kappa\n", list->start->key);
^

Answer Source

The problem is no such thing as a struct Element. clang gives a bit more of a clue in its warning.

test.c:52:25: warning: incompatible pointer types assigning to 'struct Element *' from 'Element *'
      (aka 'struct element *') [-Wincompatible-pointer-types]
            list->start = temp;
                        ^ ~~~~

You have struct element and Element but no struct Element.

typedef struct element
{
    char key;
    int value;
    struct Element* next;
} Element;

Using differing cases is risking this goof. You're better off with something like this:

typedef struct Element
{
    char key;
    int value;
    struct Element* next;
} Element_t;

Using capital letters means you won't conflict with built ins. struct Element won't conflict with anything. And Element_t makes it obvious its a type and won't conflict with variable and function names.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download