有没有办法让我的字符串大小均匀?
编辑: 我需要结构中的一些长度均匀的字符串。所以类似:
struct msg { char * 首先;字符 * 第二个;字符 * 第三个; };
所以最后就像第一个字符串“hi\0\0”第二个字符串“hello\0”第三个字符串“byebye\0\0”,我需要随时更改它们+它们是动态分配的。
最佳答案
创建一个strdup_even()
。
根据需要分配内存来复制字符串,再加上 1 block 内存以实现“偶数”。
char *strdup_even(const char *str) {
size_t len = strlen(str) + 1; // Size needed for the _string_
size_t len2 = len + len % 2; // Even allocation size
char *copy = malloc(len2);
if (copy) {
memcpy(copy, str, len);
if (len2 > len) {
copy[len] = '\0';
}
}
return copy;
}
使用示例
struct msg m;
m.first = strdup_even("hi");
m.second = strdup_even("hello");
关于更改动态 *char 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55658713/