In the code below i was expecting another output! :
#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;
}
And the output is :
CustomerId = 11W35A5CT-012345678-CORP
CustomerPhone = 012345678-CORP
CustomerDep = CORP
I was expecting this output :
CustomerId = 11W35A5CT-
CustomerPhone = 012345678-
CustomerDep = CORP
Can someone explain to me why this? Thanks.
EDIT :
To avoid confusing on my post i’m adding here the gdb trace when debugging this program:
(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"}
So whey here i see that customerId = “11W35A5CT-” and when i try printf i got the whole string?
printf()will output until it hits a\0which signals the end of the string. There’s no\0after any of the hyphens and soprintf()will print from the start position you gave it to the end of what’s intestChar.Also, you leaked away the memory the call to
mallocallocated for you. Perhaps you want to copy the string into the struct?