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?

2
  • possible duplicate of How to Initialize char array from a string Commented Feb 17, 2012 at 3: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. Commented Feb 17, 2012 at 3:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Correct. The reason the linked sample code works is because they're initializing the value at the time of declaration.
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.
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'};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.