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?
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
the C compiler will bake the string “Single” into the binary it produces, and make
labelinto a pointer to that string. In C language terms, “Single” is of typeconst char *and thus cannot be changed in any way. However, you cannot assign aconst char *to achar *, since achar *can be modified.In other words, you cannot write
because the compiler won’t allow the second line. However, you can change
info[i].nameby writing something likebecause
info[i].nameif of typechar *. To solve this problem, you should usestrncpy(I referenced a manual page above) to copy the string “{Kernel}” intoinfo[i].nameaswhich will ensure that you don’t overflow the buffer.