【问题标题】:how to store char + int as same type and same member in a struct?如何将 char + int 存储为结构中的相同类型和相同成员?
【发布时间】:2014-12-29 13:15:59
【问题描述】:

我想在一个结构中拥有一个单一类型,它采用一个 char 和一个 int 作为即 Z84。我试图弄清楚这一点,但我没有任何线索。无效的工作吗?还是和同类型的不同类型有冲突?

struct exmaple{

whatType? charValueintValue

};

我在可以存储 Z84 的女巫中搜索类似 int 的类型。 我不是这个意思:

struct exmaple{

int number
char value 
};

但是如果我可以做 printf("something:%example", example) 或者我应该怎么做才能在 charValueintValue 上使用 printf 来用 printf 打印出那个值,这会很好用?

【问题讨论】:

  • 我谨慎地犹豫着,想知道您真正要解决什么问题。
  • 在结构中存储charint 的方法是拥有char 成员和int 成员。你告诉我们你不想要那个。你没有告诉我们为什么。如果没有这些信息,就不可能说出实际问题的最佳解决方案是什么。

标签: c types struct void


【解决方案1】:

当然,这很简单:

struct example {
    char_and_int x;
};

现在你有了“结构中的单一类型”。

您只需提前定义:

struct char_and_int {
    char c;
    int  i;
};

用法:

struct example foo = { { 'Z', 89 } };

【讨论】:

  • 但是当我想打印出 x 值时如何使用 printf 呢?我应该使用什么?
  • 依次打印struct的成员:printf("%c%i", foo.c, foo.i);
【解决方案2】:

您应该将其存储为 char* 并将整数值转换为 ASCII。

struct example{
    char value[LENGHT];
};

如果要使用整数,也可以尝试分开存放:

struct example{
    char charValue;
    int intValue;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2021-04-16
    • 2019-08-05
    • 2013-11-17
    • 2020-01-08
    • 2020-03-03
    • 2020-12-23
    相关资源
    最近更新 更多