Reputation: 191
In pascal programming language i wrote the following code
Program practice;
//**** Function to get back N characters from a P position from a given string
Function get_char(s1:String;n,p :Integer): String;
Var
temp : String;
i : Integer;
Begin
temp:= s1[p];
For i:= p+1 To p+n-1 Do
temp := temp + s1[i];
get_char := temp;
End;
//**** end of the function *****
Var
s1,s2: String;
n,p: Integer;
Begin
Write('Enter the number of char:');
readln(n);
write('Enter the position:' );
readln(p);
write('Enter the string : ');
readln(s1);
write(get_char(s1,n,p));
Readkey;
End.
Know that this function gets back a certain number of characters given by the user from a certain postion in the string . for example 'hello' with p = 1 and n =2 the result will be 'he' . Now imagine p is 3 and n =4 then then the output of the function will be 'lloA'. So my question is what happends in this case or why do we get such a result ? ( please give me details if its related to memory).
Upvotes: 1
Views: 218
Reputation: 21033
When your function reads characters beyond the end of the string, it reads memory content that happens to be in those memory positions, and interpretes that memory content as characters. Memory content beyond the length of a string is not defined, nor predictable. Some compilers add an explicit Char(0)
as a terminating character. This zero character is not included in the length of the string.
To prevent wrong return values form your function, you can either,
a) turn range checking on in compiler settings, which will raise runtime errors
b) check that p + n - 1 <= Length(s)
and if not, limit reading to Length(s).
Selecting option b gives a freedom to read until the end of any string by passing MaxInt
for argument p
.
Upvotes: 5