Thread: unexpected output

  1. #1
    Registered User
    Join Date
    Oct 2014
    Posts
    74

    unexpected output

    Code:
    #include <stdio.h>#include <string.h>
    
    
    int main()
    
    
    {
        char pin [] = {1,2,3,4};
        printf("%s",pin);
        getchar();
    }
    the above code displays random symbols as opposed to 1234
    any ideas why?

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    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.

  3. #3
    Registered User
    Join Date
    Oct 2014
    Posts
    74
    thank you excellent answer

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unexpected output
    By CrimsonMagi in forum C++ Programming
    Replies: 12
    Last Post: 11-09-2013, 09:26 PM
  2. Unexpected output
    By juice in forum Windows Programming
    Replies: 6
    Last Post: 03-10-2012, 11:13 AM
  3. Unexpected output
    By juice in forum C Programming
    Replies: 24
    Last Post: 11-18-2011, 11:18 PM
  4. Unexpected output
    By GolDRoger in forum C Programming
    Replies: 9
    Last Post: 11-18-2011, 02:49 PM
  5. unexpected output
    By crash88 in forum C Programming
    Replies: 2
    Last Post: 05-16-2006, 09:03 PM