Char pointer (1): array v.s. pointer

3 common methods to declare and initialize a string:

  • char string_1[9] = “01234”;
    • declare string_1 as an array of 9 characters.
    • set the initial content of element [0] to [4].
    • the remaining elements [6],[7],[8] is initialized implicitly to zero.
    • we may later overwrite with other characters if we wish, via strcpy().
  • char string_2[  ]= ”01234”;
  • char *string_3   = “01234”;
    • create a little block of characters (somewhere in memory), and let the string_3 pointer point to it.
      • If we do “string_3 = “678””, printf(“%s”, string_3) will give you “678”.
    • we may reassign string_3 to point somewhere else, but we can’t modify the characters it points to.
      • If we do “strcpy(string_3, “567”), the program will crash.
      • If we do “string_3[0]=’5’, string_3[1]=’6’”, there is no crash, but it doesn’t work at all:  if you printf(“%c”, string3_[0]), it is still ‘0’.
      • If you initialize the pointer this way: char *string_3 = {‘1’, ‘2’, ‘\0’},  the compiler will give you a few warnings, like “initialization makes pointer from integer without a cast”, “excess elements in scalar initializer”;
      • if you do char *string_3={‘1’}, only the first warning still there.
    •  Be cautious of using “char *string = “1234””, it is dangerous/bad practice to use it, as the string is un-modifiable, and possibly you don’t reallize it until you encounter problems.

 Note: Either string_1, or string_2, or string_3, the compiler appends a ending/terminating char ‘\0’ automatically.

sizeof()               strlen()

string_1                  9                           5

string_2                  6                           5

string_3                  4                            5

 More notes:

  1. sizeof(*string_3) is 1.
  2. strlen(str) looks for ‘\0’, and return the length (not including ‘\0’).
  3. trcpy(str1, str2) copies str2 to str1, until ‘\0’ is reached, and then set the last index to ‘\0’.
  4. printf(%s”, str) either stops at ‘\0’, or stops at the number of the elements.
    • looks for ‘\0’, in order to decide the end of s string; at the same time,
    • if the sizeof the array is initialized bigger than the number of elements it was defined to, printf stops at the last element of the array.

More about the storage of a string

  1. The endianness doesn’t affect the storage of C string (character array), as in a C array, the address of consecutive array elements always increases: &a[i+1] is bigger than &[i].

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s