C structure member is a string, how to assign byte

2019-08-30 10:12发布

I am working on a simple filesystem, which (obviously) contains folders, files, etc.

A (simplified version of a) folder is represented by a structure while in RAM like so:

typedef struct{
     char label[20];
     unsigned int id;
     t_node contents[50];
 } folder;

Now, i obviously want label to contain the raw byte string with in it the name (even better would be the raw string without trailing 0, but that's a sacrifice I am willing to make).

No,here's how I create and use a struct:

folder* myFolder = (folder *) malloc(sizeof(folder));
myFolder->label = "name";

//Which doesn't work, if I try this:

char name[20] = "name";
myFolder->label = name;

//this too, doesn't work.

The error message says "incompatible types when assigning to type ‘char[20]’ from type ‘char *’". Which I understand, but don't know how to resolve.

Thanks in advance

标签: c string struct
4条回答
等我变得足够好
2楼-- · 2019-08-30 10:38

You need to use strcpy

strcpy(myFolder->label, "name");
查看更多
手持菜刀,她持情操
3楼-- · 2019-08-30 10:39

Try using strncpy():

strncpy( myFolder->label, "name", 20 );

instead of

myFolder->label = "name";

You cannot use the assignment operator to fill the array, in this case the right hand side of "name" will resolve to a char pointer.

Also I would suggest replacing the constant 20 with some defined constant indicating what the value is (ie MAX_FOLDER_LABEL_LEN).

查看更多
戒情不戒烟
4楼-- · 2019-08-30 10:49

An array is not a modifiable lvalue, so you can't assign a value to it. You have several solutions:

  • declares label as pointer to char;
  • use strcpy (or equivalent).
查看更多
甜甜的少女心
5楼-- · 2019-08-30 10:50

Use strncpy():

char name[20] = "name";
strncpy(myFolder->label, name, sizeof(myFolder->label) - 1);
myFolder->label[sizeof(myFolder->label) - 1] = 0;
查看更多
登录 后发表回答