将 char 缓冲区转换为 c 结构

标签 c casting struct

在下面的代码中,我期待另一个输出! :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _cust {
        char    customerId[10];
        char    customerPhone[10];
        char    customerDep[4];
} cust;

int main(int argc, char **argv) {
        cust    *newCust;
        const char testChar[] = "11W35A5CT-012345678-CORP";

        newCust = (cust *)malloc(sizeof(struct _cust));
        newCust = (cust *)testChar;

        printf("CustomerId = %s\n", newCust->customerId);
        printf("CustomerPhone = %s\n", newCust->customerPhone);
        printf("CustomerDep = %s\n", newCust->customerDep);

        return 0;
}

输出是:

CustomerId = 11W35A5CT-012345678-CORP
CustomerPhone = 012345678-CORP
CustomerDep = CORP

我期待这个输出:

CustomerId = 11W35A5CT-
CustomerPhone = 012345678-
CustomerDep = CORP

谁能给我解释一下这是为什么?谢谢。

编辑:

为了避免混淆我的帖子,我在调试此程序时在此处添加了 gdb 跟踪:

(gdb) b main
Breakpoint 1 at 0x8048474: file name.c, line 11.
(gdb) run
Starting program: /home/evariste/src/customer_files/a.out 

Breakpoint 1, main (argc=1, argv=0xbffff2c4) at name.c:11
11  int main(int argc, char **argv) {
(gdb) n
13      const char testChar[] = "11W35A5CT-012345678-CORP";
(gdb) n
15      newCust = (cust *)malloc(sizeof(struct _cust));
(gdb) n
16      newCust = (cust *)testChar;
(gdb) n
21      printf("CustomerId = %s\n", newCust->customerId);
(gdb) print *newCust
$1 = {customerId = "11W35A5CT-", customerPhone = "012345678-", 
  customerDep = "CORP"}

所以我在这里看到 customerId = "11W35A5CT-"并且当我尝试 printf 时我得到了整个字符串?

最佳答案

printf() 将一直输出,直到遇到 \0 表示字符串结束为止。在任何连字符之后都没有 \0,因此 printf() 将从您给它的开始位置打印到 testChar.

此外,您泄漏了调用为您分配的 malloc 的内存。也许您想将字符串复制到结构中?

关于将 char 缓冲区转换为 c 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9960927/

相关文章:

c - 是否可以在普通的 `void *` 中设计没有 `c` 指针的通用数据结构?

ios - 从 'UIViewController' 转换为不相关类型 'TableViewCell' 总是失败

c - 结构 vector c

创建 mpi 派生数据类型,包含带指针的结构

c - c11 _Generic 通用关联的结果表达式的每个分支是否都必须有效?

c - c中的strlen错误

c++ - 如何计算 cilk_spawn 的时间

java - 转换 JDBCTemplate.QueryForObject 的返回值

swift - 如何在 swift 中使用带有开关的 AS 来获取类类型

json - 带有结构数组的 Golang 和 JSON