在下面的代码中,我期待另一个输出! :
#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/