C structure member is a string, how to assign byte

2019-08-30 10:15发布

问题:

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

回答1:

Use strncpy():

char name[20] = "name";
strncpy(myFolder->label, name, sizeof(myFolder->label) - 1);
myFolder->label[sizeof(myFolder->label) - 1] = 0;


回答2:

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).



回答3:

You need to use strcpy

strcpy(myFolder->label, "name");


回答4:

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).


标签: c string struct