When you declare an array of char
as you have done:
char str[10] = "Jessica";
then you are telling the compiler that the array will hold up to 10
values of the type char
(generally - maybe even always - this is an 8-bit character). When you then try to access a 'member' of that array with an index that goes beyond the allocated size, you will get what is known as Undefined Behaviour, which means that absolutely anything may happen: your program may crash; you may get what looks like a 'sensible' value; you may find that your hard disk is entirely erased! The behaviour is undefined. So, make sure you stick within the limits you set in the declaration: for str[n]
in your case, the behaviour is undefined if n < 0
or n > 9
(array indexes start at ZERO). Your code:
printf("%c\n", str[15]);
does just what I have described - it goes beyond the 'bounds' of your str
array and, thus, will cause the described undefined behaviour (UB).
Also, your scanf("%s", &str);
may also cause such UB, if the user enters a string of characters longer than 9 (one must be reserved for a terminating nul
character)! You can prevent this by telling the scanf
function to accept a maximum number of characters:
scanf("%9s", str);
where the integer given after the %
is the maximum input length allowed (anything after this will be ignored). Also, as str
is defined as an array, then you don't need the explicit "address of" operator (&
) in scanf
- it is already there, as an array reference decays to a pointer!
Hope this helps! Feel free to ask for further clarification and/or explanation.