Initializing strings

This is a discussion on Initializing strings within the C Programming forums, part of the General Programming Boards category; Unfortunately, being a self-taught programmer, I can't go to a teacher and get this question answered easily, so I have ...

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    17

    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).
    Code:
    For example:
    char array_hi[3]={'H', 'i', '\0'};
    A second way is to initialize it as a string constant.
    Code:
    char array_hi[3]="Hi";
    
    or....
    
    char array_hi[]="Hi";
    The third way is to use a character pointer and then initialize the pointer with a string constant, like

    Code:
    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,588
    This
    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.

    Use
    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, 09:16 AM
  2. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 02:24 PM
  3. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 07: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21