the above code displays random symbols as opposed to 1234Code:#include <stdio.h>#include <string.h> int main() { char pin [] = {1,2,3,4}; printf("%s",pin); getchar(); }
any ideas why?
the above code displays random symbols as opposed to 1234Code:#include <stdio.h>#include <string.h> int main() { char pin [] = {1,2,3,4}; printf("%s",pin); getchar(); }
any ideas why?
Several things you seem to be confused about:
- A char is just a small integer. Certain integer values correspond to symbols displayed on the screen*. The numbers 1, 2, 3 and 4 have the right numerical values, but are distinct from the characters that produce the digits '1', '2', '3' and '4'.
- The %s modifier for printf expects a C string: a sequence of characters adjacent in memory and terminated with a null character (i.e. '\0'). pin is not null-terminated, so printf doesn't know when to stop printing numbers
- You can either store pin as a regular int and print it with a single printf("%d", pin); as an array of digits (like you currently are) and print it with a for loop that uses the length of the array and prints each digit individually printf("%d", pin[i]); or store pin as an actual string, by adding a null terminator, or initializing with a string literal: char pin[] = {'1', '2', '3', '4', '\0'}; or char pin[] = "12345"; Using double quotes for a string literal automatically puts a null terminator in there for you, so long as the array has room (leaving the [ ] empty will automatically make pin the right size for the initialized data).
* The symbol/grapheme associated with a particular numerical value depends on the character sets used, such as ASCII, EBCDIC. ASCII-compatible character sets are the most common, but others are still used, albeit rarely, hence it's recommended to use a character literal 'A' instead of 65 or 0x41 if you want to refer to upper case A.
thank you excellent answer