Understanding ways of array declaration and input

Hi,
I want to understand the ways in which arrays can be declared and used. It would be great if anyone could tell what each of the following do or what's the difference between them and what would be the length of each:-

1 - char ary1[50];

2 - char ary2[50] = {'H','e','l','l','o'};

3 - char ary3[50] = {'H','e','l','l','o','\0'};

4 - char ary4[50] = {'\0'};

5 - char ary5[50] = {'\0','H','e','l','l','o'};

6 - char ary6[50] = {'\0','H','e','l','l','o','\0'};
They all declare an array that can hold up to 50 char elements.
The only difference is how they're initialized.

1 - nothing is initialized, so the array contains 50 "garbage" values
2 - The first 5 elements are initialized to the characters of "Hello", and the rest are initialized to their default values (null characters in this case)
3 - Same as 2, except you explicitly wrote in the null character for the 6th character of the array
4 - Initializes the first element to the null character and all other elements to their default values (which just so happens is also the null character)
5 - Sets the first 6 characters to the characters of "\0Hello" and the rest to their default values (null characters)
6 - Same as 5, except you explicitly wrote in the null character for the 7th character.

In terms of what happens if you treat them like C strings, since C strings end with a null terminator, any function that operates on C strings (and expects to see a null character at the end of the string) will correctly recognize #2 and #3 as the string "Hello", but since #4,5, and 6 both start with a null character, it'll think that those strings are empty.
#1 is uninitialized, so don't try to do anything with it until you initialize it.

So, in terms of the "length" of each one, they all have 50 elements, but if you meant the length of the string (i.e. the result returned by calling strlen on it), this is what you'll get:
1 - ??? (undefined -- don't try it)
2 - 5
3 - 5
4 - 0
5 - 0
6 - 0
Last edited on
Thank you very much long double main. I wasn't expecting such an extensive reply but thanks anyway :)
Topic archived. No new replies allowed.