how to set char array to string in c

15,779

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.

Share:
15,779
help
Author by

help

Updated on November 21, 2022

Comments

  • help
    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
      Cody Gray about 12 years
    • Vaughn Cato
      Vaughn Cato about 12 years
      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.
  • Cody Gray
    Cody Gray about 12 years
    Correct. The reason the linked sample code works is because they're initializing the value at the time of declaration.
  • ugoren
    ugoren about 12 years
    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.