【问题标题】:How to print three bytes in a struct in C如何在C中的结构中打印三个字节
【发布时间】:2011-03-08 06:58:53
【问题描述】:

我有以下 C 代码:

person->title

标题是一个三字节字符数组。我要做的就是打印这三个字节。我不能将字符串格式化程序与 printf 一起使用,因为没有空字节。

如何在不复制或添加空字节的情况下打印出来?

提前致谢!

更新

原来它不是一个数组,只是三个相邻的字节。如果我尝试使用建议的代码进行编译:

人->职称[0]

失败并出现错误:

test.c:46: error: subscripted value is neither array nor pointer.

【问题讨论】:

  • 除非该解决方案不起作用,因为 printf 仍在寻找空字节。使用该解决方案(我之前尝试过)会导致 strnlen() 中的段错误。我希望我错过了一些东西,因为那将是一个很棒的解决方案......
  • 如果你可以扩展你的数组来解释一个终止符,'\0'。这将允许您使用字符串函数,而不是编写自己的数组访问函数。我相信一个额外的角色值得节省开发时间。

标签: c struct printf


【解决方案1】:
printf("%c%c%c",person->title[0],person->title[1],person->title[2]);

【讨论】:

    【解决方案2】:

    请试试这个....

    char *a = &(person->title);
    printf("%c %c %c", *a, *(a+1) , *(a+2));
    

    编辑

    基于结构中的 20 个字段,它更简单的配对,在结构的情况下发生连续的内存分配

    例如:

    struct test {
     // Suppose the elements of the struct are only title and name each having 3 bytes
    }*person;
    
    // The first 3 bytes are w.r.t title and the very next 3 is allocated to name, note for 
    // struct it`s stored as contiguous memory allocation
    
    
    // code can be rewritten as - to display title and name
    
    char *a = &(person->title);
    printf("Title : %c%c%c", *a, *(a+1), *(a+2));
    printf("Name : %c%c%c", *(a+3), *(a+4), *(a+5));
    

    【讨论】:

    • @NimalGeo 效果很好 - 但是该结构有大约 20 个字段,如果我必须为每个字段都这样做,那将是一个真正的痛苦...... :(
    • 尝试复制编辑部分的代码应该可以解决我猜
    • 你可以循环显示输出:-)
    • 在struct 中,只有数组是连续的。允许编译器在字段之间插入 padding,例如以满足对齐可访问性。
    【解决方案3】:

    你可以使用类似的东西:

    printf("%c%c%c", person->title[0], person->title[1], person->title[2]);
    

    如果您确定这三个字节已填满。如果它可能短于三个字节,请尝试以下操作:

    for (int i=0; (i<3) && (person->title[i] != 0); i++)
      printf("%c", person->title[i]);
    

    【讨论】:

    • 不是以null结尾的,所以即使小于3个字节,第二次检查也没用(:
    • 我在想它可以包含“Mrs”、“Mr.”或有时只是“M”的情况。例如。即不是正常意义上的空终止,但可能总短于 3 个字符。
    【解决方案4】:

    对于结构 - 您可以利用内存将被分配为连续字节的事实。您还可以使用 fwrite() 来准确控制写入的字节数(如果您希望将“stdout”用作文件指针,则将其打印到终端)。

    例如

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct _test
    {
      char title[3];
      char job[4];
      char other[5];
    } Test;
    
    int main(int argc, char* argv)
    {
      Test test;
    
      strcpy(test.title,"MR_");
      strcpy(test.job,"1234");
      strcpy(test.other,"OTHER"); 
    
      fwrite(&test,1,sizeof(Test),stdout);
      printf("\n");
    }
    

    将输出:

    MR_1234OTHER
    

    【讨论】:

      猜你喜欢
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      相关资源
      最近更新 更多