why we can access more information than the lenght of the array?
I thought that after the Null (0) the array ends. Why we can access position 40?
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.Sign up to join this community
So, in C, strings don't really exist in the same way that they do in other languages. A string is a char array. C also does not pass strings and arrays between functions, but pointers to the locations in memory where the starting location of the data can be found. In short, this means that what is being passed to
printf is not the string
s, but a binary address (pointer) to where the start of the
s char array can be found. Because only the start address is sent, and no ending address, the function will continue reading until it is told to stop or the program crashes. This allows for
s to exist when
s is only 4 characters long (including the terminal character).
This fact that pointers are passed and not the array itself can lead to unexpected results when a function starts accessing data beyond the bounds/end of the array, as is done here with
s. This is something we must be careful of in these situations.
I hope this helps clear things up for you. If it does, feel free to click the check mark beside this answer to accept it. If not, let me know and I will try to help/explain more.