Issue
Your string length should be one more than the maximum number of characters you want it to be able to hold. Logical enough: strings are terminated with a NULL
character.
It's a very general advice that most newbies get. However, as I grew in programming, now it seems that it's not so correct.
The indexing of any type of array, be it int
or char
, starts from 0
. The maximum index value of most arrays, therefore, is one less than its numerical value. It's same with a string, but since it has an extra character at the end, it gets incremented by one. So, the string length is the same as the number of characters in it.
To see if I'm right, see this snippet:
char str[9];
scanf("%s", str);
printf("%d", strlen(str));
Make this a full-fledged program, and run it. Type 123456789
, a guaranteed 9-character long text, and see the results. It could hold the string and sure enough, the string length is 9
.
I even witnessed many expert programmers saying that string size should be plus one its capacity. Is this advice largely a myth, or I am going wrong somewhere?
EDIT
Let's say I want to create an integer array Arr
that can hold x
number of elements. The index value of Arr
's last element will be one less than x
since index values start from 0
and not 1
. So, its length is x-1
.
How would you declare it then? I'd do that like this: int Arr[x-1];
. I don't think there's any issues with this.
Now if Arr
were a char
type array (i.e. a string), the length of Arr
would be one more than that of its int
counterpart since it has an extra NULL character at the end. This will end up as: (x-1)+1=x
.
So why does the declaration this time has to be char Arr[x+1]
and not simply char Arr[x]
?
Solution
You're right about the indexing. However:
char str[9];
When you declare a string this way, the number 9
is the array length. Minus the NULL, there can be only 8 characters, not 9. The length of an array is the number of elements in the array, NOT the maximum index value as you think. You're confusing these terms.
Why your program works is already explained by many other answers and even comments.
Answered By - user5084667 Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.