1

so i have a struct call Process_Info

  struct Process_Info {
    char name[128];
    int pid;
    int parent_pid;
    int priority;
    int status;
      };

and an array of Process_Info call info. I set pid in info to an integer, it works but when I try to set name in info to "{kernel}" like this

info[i].name="{kernel}";

and it give me incompatible type in assignment error. I search online it seem i can do this, like in http://www.cs.bu.edu/teaching/cpp/string/array-vs-ptr/, they did char label[] = "Single"; So what am i doing wrong?

help
  • 809
  • 5
  • 18
  • 35
  • possible duplicate of [How to Initialize char array from a string](http://stackoverflow.com/questions/963911/how-to-initialize-char-array-from-a-string) – Cody Gray - on strike Feb 17 '12 at 03:58
  • 1
    Unfotunately, what you can do in an assignment isn't the same as what you can do in an initialization, even though they look similar. – Vaughn Cato Feb 17 '12 at 03:59

2 Answers2

8

The short answer: A C compiler will bake constant strings into the binary, so you need to use strncpy (or strcpy if you aren't worried about security) to copy "{kernel}" into info[i].name.

The longer answer: Whenever you write

char label[] = "Single";

the C compiler will bake the string "Single" into the binary it produces, and make label into a pointer to that string. In C language terms, "Single" is of type const char * and thus cannot be changed in any way. However, you cannot assign a const char * to a char *, since a char * can be modified.

In other words, you cannot write

char label[] = "Single";
label[0] = "T";

because the compiler won't allow the second line. However, you can change info[i].name by writing something like

info[i].name[0] = '[';

because info[i].name if of type char *. To solve this problem, you should use strncpy (I referenced a manual page above) to copy the string "{Kernel}" into info[i].name as

strncpy(info[i].name, "{Kernel}", 256);
info[i].name[255] = '\0';

which will ensure that you don't overflow the buffer.

ugoren
  • 16,023
  • 3
  • 35
  • 65
Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52
  • 2
    Correct. The reason the linked sample code works is because they're initializing the value at the time of declaration. – Cody Gray - on strike Feb 17 '12 at 03:57
  • Not very accurate. In you first example, `label` is an array, not a string, and it's certainly possible to modify it. C allows initializing an array by a literal string, but doesn't allow assigning it. – ugoren Feb 17 '12 at 05:43
0

I think you may be mistaken. The way you would assign this would be one char at a time like so...

name[] = {'a','b','c','d'};
zellio
  • 31,308
  • 1
  • 42
  • 61
Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236