如何做很容易在C ++中未结束的字符数组? [英] How readily do unterminated char arrays in C++?

查看:134
本文介绍了如何做很容易在C ++中未结束的字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是可以解决的通过谷歌 - 我无法找到任何东西。

Sorry if this is solvable via Google -- I couldn't find anything.

char foo[4] = "abcd";

是在C无效++(由于需要关于'\\ 0'终止子)但在C IIRC有效? - 是正确

is invalid in C++ (due to the need for '\0' terminator) but IIRC valid in C -- is that correct?

我有一组结构与大量的是要填补空白的,而不是'\\ 0'结尾定长字的字段。我希望能够做的通常的排序结构初始化 - 你知道

I have a set of structs with a large number of "fixed length" character fields that are to be blank-padded and not '\0' terminated. I would like to be able to do the usual sort of struct initialization -- you know

mystruct bar = {17, "abcd", 0x18, "widget  ", ...

但我不能这样做,在C ++。一个解决方案我猜是把所有的初始化结构是这样的到自己的C(不++)源模块。我试图避免难看的,费力的解决方案是

But I can't do that in C++. One solution I guess would be to put all of the initialized structs like this into their own C (not ++) source module. The ugly, laborious solution that I am trying to avoid is

mystruct bar = {17, {'a', 'b', 'c', 'd'}, 0x18, {'w', 'i', 'd', 'g', 'e', 't', ' ', ' '}, ...

是否有一个良好的C ++解决方案?一个聪明的宏,将有效地让ABCD是char [4]没有'\\ 0'终结?

Is there a good C++ solution? A clever macro that will effectively let "abcd" be char[4] with no '\0' terminator?

谢谢,
查尔斯

Thanks, Charles

推荐答案

您可以使用宏将做的工作:

You could use a macro that will do the job:

#define MACRO_GET_1(str, i) \
    (sizeof(str) > (i) ? str[(i)] : 0)

#define MACRO_GET_4(str, i) \
    MACRO_GET_1(str, i+0),  \
    MACRO_GET_1(str, i+1),  \
    MACRO_GET_1(str, i+2),  \
    MACRO_GET_1(str, i+3)

#define MACRO_GET_STR(str) MACRO_GET_4(str, 0)

struct mystruct {
    char foo[4];
};

int main() {
    mystruct obj{ MACRO_GET_STR("abcd") };
    const char* str = "abcd";
    std::cout << memcmp(obj.foo, str, 4); // 0

    return 0;
}

<大骨节病>

这code基于这个解决方案,它也易于扩展。

This code is based on this solution and it is also easily extendable.

反正有一个建议前段时间大概从未到标准。有周围的补丁,让字符串转换成可变参数炭包。

Anyway there was a proposal some time ago that probably never made it to the standard. There are patches around that allow string literals to be converted into variadic char packs.

这篇关于如何做很容易在C ++中未结束的字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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