Originally Posted by
X PaYnE X
but i dont get 1 thing.. your declaring it as sword[4].. which is 4 elements (0-3) i get that, but.. what is the 5th element (sword[4]) used for?
There is no sword[4].
When you go like this: You're actually creating 4 slots (including 0):
Code:
sword[0] = '1';
sword[1] = '2';
sword[2] = '3';
sword[3] = '4';
The only reason we always put '\0' is so that when we use the char array as a string, like: The function puts(char *output) will know when to stop, because it stops printing out sword when it hits the '\0' character. But if you're using the char array to just hold characters, and not to do any string manipulation, then it'll be ok as long as you have a variable that holds how many characters are in the char array. Here's some examples:
Code:
char sword[4];
sword[0] = '1';
sword[1] = '2';
sword[2] = '3';
sword[3] = '4';
/* We know it's 4 characters long, but strlen() does not. */
printf("%i\n", strlen(sword));
But if we go like this:
Code:
char sword[5];
sword[0] = '1';
sword[1] = '2';
sword[2] = '3';
sword[3] = '4';
sword[4] = '\0';
/* It knows the length of the string is 4 characters long!*/
printf("%i\n", strlen(sword));