C,将长度 <=60 的字符串存储在 space 中,用于大小为 15 的无符号整数数组

C, Storing a string with length <=60 in the space for an array of unsigned ints of size 15

这个问题把我搞糊涂了-

我有一个数组(固定大小):

unsigned int i_block[15];

我有一个字符串(长度 <= 60):

"path/to/bla/is/bla"

如何将字符串的字符存储在数组的 space 中? 我正在考虑也许使用 memset,但我不知道这是否可行?

供参考: "If the data of a file fits in the space allocated for pointers to the data, this space can conveniently be used. E.g. ext2 stores the data of symlinks (typically file names) in this way, if the data is no more than 60 bytes ("快速符号链接")."

来自

Source

此代码假定 int 类型使用 4 个字节,因此 15 int 使用 60 个字节。

您可以这样存储字符串:

size_t len = strlen(str);
if (len <= sizeof i_block) {
    memset(i_block, 0, sizeof i_block);
    memcpy(i_block, str, len);
}

数组应该用 '[=13=]' 填充以保持整洁并提供一种判断字符串长度的方法。上面的代码简单易读。您可以复制字符串并将缓冲区的其余部分设置为 0,并稍微降低对 memset.

的可读性调用

请注意,如果字符串长度为 60,则数组末尾不会有尾随 '[=13=]'。应仔细检索字符串以解决此限制。