0

Here is my code which I would expect it to compile, but it does not:

#include <stdio.h>
#include <stdlib.h>

typedef struct turtle {
    char name[20];
    int age;
} turtle;

int main(){

    turtle koray = {"koray",25};
    turtle halim;

    halim.name = "halim"; // This line will cause in compile error.
    halim.age = 25;

    printf("%s\n",koray.name);
    printf("%s\n",halim.name);

}

What am I doing wrong?

This complies successfully, but prints garbage:

*(halim.name) = "halim";

by garbage I mean:

koray
p
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
  • Doesn't the compiler warn in anger for this `halim.name = "halim";`? – alk Mar 20 '15 at 12:49
  • It should tell you ... - read the warning. – alk Mar 20 '15 at 12:50
  • @alk It says: array type 'char [20]' is not assignable but I do not understand why.. – Koray Tugay Mar 20 '15 at 12:50
  • Just because arrays in C are not assignable. It's made this way. – Matt Mar 20 '15 at 12:55
  • @KorayTugay.: My answer was correct but I have unnecessarily used the terms like "deep copy" or "shallow copy". These are the concepts in c++. If interested you can find it http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy Sorry for inconvenience. I have removed my answer. – user2736738 Mar 20 '15 at 13:17

2 Answers2

3

You can figure out by reading the error message.

error: incompatible types in assignment of ‘const char [6]’ to ‘char [20]’

"halim" is a const char [6] and name is a char [20], and they cannot be assigned directly.

Use strcpy() instead.

strcpy(halim.name,"halim");
Community
  • 1
  • 1
shauryachats
  • 9,975
  • 4
  • 35
  • 48
  • ah I see.. My compiler is not exact as yours I guess. It only says: ../hello.c:14:13: error: array type 'char [20]' is not assignable and it was confusing.. Thanks.. – Koray Tugay Mar 20 '15 at 12:51
  • @KorayTugay That warning is also OK. Arrays aren't assignable, even if the types (which include the lengths) match. I would say your compiler warning is actually less misleading than the one in this answer. – juanchopanza Mar 20 '15 at 12:56
1

In C array cannot be assigned. (They can be initialised on definition however).

To fill a C-"string" use strcpy():

strcpy(halim.name, "halim");
alk
  • 69,737
  • 10
  • 105
  • 255