0

Why can't I assign a string of chars to the chars array that I have created in the struct node. I tried to follow Zamyla tutorial and it seemed to work in there but when I am trying to just do this assignment I am getting this error :

main.c:21:18: error: array type 'char [2]' is not assignable
cursor->word = "dsds";

Here comes my code.

            typedef struct node
            {
               char word[2];
               struct node* next;
            }
            node;


             int main(int argc, char* argv[])
             {

             node* cursor = (node*) malloc(sizeof(node));
             cursor->word = "dsds";
             printf("%s",cursor->word[0]);

             }

Can someone explain why please?

Just by the way this assigning would work if I tried to assign a single character like 'd' to the cursor->word[0] and than I would get a standard output of 'd' in the console.

1

You are trying to assign a string literal to an array of characters. You'll need to do something like

        #include <string.h>

        typedef struct node
        {
           char word[2];
           struct node* next;
        }
        node;


         int main(int argc, char* argv[])
         {
             node* cursor = (node*) malloc(sizeof(node));
             strcpy(cursor->word, "dsds");
             printf("%s",cursor->word);
             return (0);
         }
4
  • I think that the code you have proposed is the same as what I have tried Darc. Unless I am missing some detail in there, when I tried to just copy/paste it to "cs50 io" it gives me the same error. – Kamil Kug Sep 9 '16 at 13:47
  • @user13605 My mistake. I pasted your own snippet without editing it first. – Darc Nawg Sep 9 '16 at 15:18
  • @user13605 Don't forget to also free your allocated memory. – Darc Nawg Sep 9 '16 at 15:23
  • Thank you man. I have tried with this strcpy indeed and it does work at least I know that the way that was presented in the cs50 walkthrough is not doable hehe. Thank you again and I mark it as answered!! – Kamil Kug Sep 9 '16 at 19:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .