Thread: simple question about strings

  1. #1
    Registered User
    Join Date
    Sep 2005

    simple question about strings

    hello, I'm trying to learn about strings and I wrote this simple piece of code to try and print out: ABCD

    but it prints out some weird characters after D

    it puts out: ABCD "

    and some other symbol not on my keyboard, does anyone know why?

    thank you

    here's the code I wrote:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    main()    {
    char string1 [] = { 'A' , 'B' , 'C' , 'D' } ;

  2. #2
    Registered User
    Join Date
    Oct 2005

    Re: simple question about strings

    In C, a string is a collection of characters terminated by the null character, which is simply the character with value zero. Your code has a collection of characters, but does not include a null character, so it's not a string. printf()'s %s conversion specifier expects a string (really, a pointer to one), so what you're passing causes undefined behavior. You could do:

    char string1[] = { 'A', 'B', 'C', 'D', 0 };
    You could also write this as:

    char string1[] = "ABCD";
    In this case, "ABCD" automatically includes the null character for you.

    Your code results in undefined behavior, which technically means anything can happen. What's really happening, though, is that there is random junk after the 'D' in your array that printf() prints out. It will print out as much random junk as it can until it finds a null character, or if you're on a modern operating system, you try to read memory that's outside of your address space.

  3. #3
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Sydney, Australia
    Edit: I'm too slow.

    Strings in C need to be null terminated. You haven't terminated "string1" with a null character ('\0'), printf will keep reading from string1 until a null character is hit.

    char string1[] = { 'A', 'B', 'C', 'D', 0 };
    char string1[] = "ABCD";
    In the second case, the string is implicitly null terminated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple question regarding variables
    By Flakster in forum C++ Programming
    Replies: 10
    Last Post: 05-18-2005, 08:10 PM
  2. Simple class question
    By 99atlantic in forum C++ Programming
    Replies: 6
    Last Post: 04-20-2005, 11:41 PM
  3. Simple question about pausing program
    By Noid in forum C Programming
    Replies: 14
    Last Post: 04-02-2005, 09:46 AM
  4. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 12:15 PM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM