how to set char array to string in c
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.
help
Updated on November 21, 2022Comments
-
help over 1 year
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?
-
Cody Gray about 12 yearspossible duplicate of How to Initialize char array from a string
-
Vaughn Cato about 12 yearsUnfotunately, what you can do in an assignment isn't the same as what you can do in an initialization, even though they look similar.
-
-
Cody Gray about 12 yearsCorrect. The reason the linked sample code works is because they're initializing the value at the time of declaration.
-
ugoren about 12 yearsNot 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.