0

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?

enter image description here

1

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[40] 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[40]. 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.

1
  • Make for sense. good job – Peterv Jun 5 at 17:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .