0

I have a struct containing the command char var_name[200]; and a typedef after it (typedef struct list_var* data) and I have a function that gets the parameter char* var. In this function I try the following:

data new_var = (data) malloc(sizeof(struct list_var));
new_var->var_name = var

But in this line I get an error, saying "incompatible types when assigning to type char[200] from type char*.

Please help me.

user5638730
  • 495
  • 2
  • 9
  • 22

3 Answers3

3

Check out this post: Char array in a struct - incompatible assignment?

Arrays are not assignable in C. You need to use strcpy.

strcpy(new_var->var_name, var);
Community
  • 1
  • 1
Alex Parker
  • 1,533
  • 3
  • 16
  • 38
1

use strcpy to copy strings:

strcpy(new_var->var_name, var);
Pooya
  • 6,083
  • 3
  • 23
  • 43
0
data new_var = (data) malloc(sizeof(struct list_var));

You now have allocated memory for a struct data, which includes memory for 200 characters, the array new_var->var_name.

new_var->var_name = var;

Now you want to assign a char * -- i.e. a pointer -- to an array of 200 characters.

Yes, yes, I know, we call both character arrays and character pointers "strings" at times, but that is just a mental shortcut, and it makes us think the wrong thing pretty often.

You wouldn't expect this here to work either:

int array[200];
int x = 42;
array = &x;

Why should it work for char[] / char*?

What you want is strcpy / strncpy.

DevSolar
  • 67,862
  • 21
  • 134
  • 209