-1

If I use a list like this:

typedef struct list {
    char information[20];
    struct list *next;
}

And if I try to pass the information through parameter of a function, for example:

list *createlist(char inf[]) {
    list *l = (list*)malloc(sizeof(list));
    l->information = inf;
    l->next = NULL;
    return l;
}

It does not work, the error is

[Error] incompatible types in assignment of 'char*' to 'char [20]'

If i declare information like char *information and in fuction list *createlist(char *inf), in this way it works, but the string is limited to 7 characters. How can I fix this?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 2
    Please [see why not to cast](http://stackoverflow.com/q/605845/2173917) the return value of `malloc()` and family in `C`. – Sourav Ghosh Jun 26 '15 at 11:54
  • 1
    http://stackoverflow.com/questions/11864410/string-assignment-in-c If someone can find a better duplicate please post it. – Lundin Jun 26 '15 at 11:57

2 Answers2

1

Arrays are not assignable. You'll have to copy the characters manually. Fortunately, there is a function called strcpy(from string.h) that does this for you. So change

l->information=inf;

to

strcpy(l->information, inf);

Sidenotes:

  • Check the return value of malloc to see if it was successful.
  • Make sure that inf consist of a maximum of 19 characters (+1 for the NUL-terminator) to prevent a buffer overflow.
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
1

In your case, information is of type "array". In the code

l->information=inf;

is the issue, as you cannot assign arrays.

If you meant to copy the contents, you need to use strcpy() function, declared in string.h header.

That said,

  1. Please see why not to cast the return value of malloc() and family in C.

  2. Always check the return value of malloc() for success before using the returned pointer.

  3. Add the proper typedef for list. You need to write it like

    typedef struct list {
        char information[20];
        struct list *next;
    }list;
    
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261