Thread: Initializing strings

  1. #1
    Registered User
    Join Date
    Mar 2002

    Initializing strings

    Unfortunately, being a self-taught programmer, I can't go to a teacher and get this question answered easily, so I have to rely on others.

    The question is on initializing strings. There are three basic ways to do it. One way is to initialize it as a character array with specific characters and the null character (\0).
    For example:
    char array_hi[3]={'H', 'i', '\0'};
    A second way is to initialize it as a string constant.
    char array_hi[3]="Hi";
    char array_hi[]="Hi";
    The third way is to use a character pointer and then initialize the pointer with a string constant, like

    char *ptr_hi="Hi";
    Now, my question is this. When to use which method? The first method seems rather bulky, with the second being more streamlined version of it. But, why would you use the third? Or is it just a matter of preference?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    char array_hi[]="Hi";

    is almost always preferred to this
    char array_hi[3]="Hi";

    Simply because you get the compiler to do the counting for you. In addition, you could edit the string thus
    char array_hi[3]="Hit";
    and it would not be a compile time error, but you lose the \0 at the end - the result of which, the array is no longer a valid string.

    char *ptr_hi="Hi";

    When you have no intention of modifying the string, or you have some intention of making ptr_hi point elsewhere

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. initializing 2d strings
    By Fox101 in forum C Programming
    Replies: 6
    Last Post: 02-05-2008, 10:16 AM
  2. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  3. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  4. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM
  5. Initializing Strings
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 04-22-2002, 03:59 PM