的C结构成员是一个字符串,如何直接分配字节 [英] C structure member is a string, how to assign bytes directly

查看:205
本文介绍了的C结构成员是一个字符串,如何直接分配字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个简单的文件系统,(显然)包含文件夹,文件等。

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

一个文件夹(一个简化版本)是由一个结构psented重新$ P $,而在RAM中,像这样:

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;

现在,我当然希望标签包含原始字节串与它的名字(甚至更好的将是原始字符串没有后面的0,但这是牺牲我愿意做)。

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.

分配给从类型类型的char *''的char [20]'时不兼容的类型错误消息说。
我的理解,但不知道如何解决。

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.

在此先感谢

推荐答案

使用函数strncpy()

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

这篇关于的C结构成员是一个字符串,如何直接分配字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆