在下面的代码中我期待另一个输出!:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
CustomerId = 11W35A5CT-012345678-CORP
CustomerPhone = 012345678-CORP
CustomerDep = CORP
Run Code Online (Sandbox Code Playgroud)
我期待这个输出:
CustomerId = 11W35A5CT-
CustomerPhone = 012345678-
CustomerDep = CORP
Run Code Online (Sandbox Code Playgroud)
有人能解释一下为什么这样吗?谢谢.
编辑:
为了避免混淆我的帖子,我在调试这个程序时在这里添加了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"}
Run Code Online (Sandbox Code Playgroud)
所以乳清在这里,我看到customerId ="11W35A5CT-",当我尝试printf时,我得到了整个字符串?
printf()将输出,直到它命中一个\0信号结束字符串.\0在任何连字符之后都没有,所以printf()将从你给它的开始位置打印到结尾的位置testChar.
此外,你泄露了malloc为你分配的呼叫的内存.也许你想将字符串复制到结构中?