I've been hung up on this for the past two hours, and it's really starting to irritate me. I'm using standard C, trying to print a char array's element.
The following is a snippet that works(prints entire array),
CreditCard validate_card(long long n) {
CreditCard cc; // specify new credit card
cc.n = n; // specify card num as passed
cc.valid = false; // initialize as invalid
cc.type = AEX; // initialize at american express
bool valid;
char s[20];
sprintf( s, "%d", n ); // convert credit card number into char array
printf("%s\n", s);
return cc;
}
The following snippet does not work,
CreditCard validate_card(long long n) {
CreditCard cc; // specify new credit card
cc.n = n; // specify card num as passed
cc.valid = false; // initialize as invalid
cc.type = AEX; // initialize at american express
bool valid;
char s[20];
sprintf( s, "%d", n ); // convert credit card number into char array
printf("%s\n", s[0]);
return cc;
}
On that note, if anyone could also too explain to me how to concatinate char array elements to char pointers, I'd be grateful.
When you use this line.
printf("%s\n", s[0]);
The compiler should print some warning about mismatch of the format string %s
and the corresponding argument, s[0]
.
The type of s[0]
is char
, not char*
.
What's your intention?
If you want to print just one character, use:
printf("%c\n", s[0]);
If you want to print the entire array of chracters, use:
printf("%s\n", s);
You need to replace below line
printf("%s\n", s[0]);
with
printf("%c\n", s[0]);
to print 1 character.
To print all characters 1 by 1, use a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With