(15pt) Consider the function below, where you get a pointer pi to the first and
ID: 3725901 • Letter: #
Question
(15pt) Consider the function below, where you get a pointer pi to the first and a pointer p2 to the last character of the same string. The function should return a pointer to the character in the middle of the string (in case of an even size consider the leftmost). char *midchar (char *p1, char *p2) ( return (p1 + p2) / 2; A thoughtful 212 student should notice that adding together pointers is likely to be disastrous Memory addresses tend to be very large. The operation above is very likely to lead to overflow Rewrite the function above in order to avoid the overflow,Explanation / Answer
A pointer is a variable which contains address of another variable. Addition, multiplication or division of pointer makes no sense. It would lead to overflow obviously, also you would have no idea what it would point to. But the difference of two pointers gives you offset between two addresses. This can be useful in case of an array.
So, to find the mid pointer of a string :
if n is the length of the string then offset between extreme pointers(p2 -p1) gives n-1, and midpointer would be p1+(n-1)/2 (it considers leftmost in case of even size)
char *midchar(char* p1,char *p2)
{
char *mid = p1 + (p2 - p1)/2;
return mid;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.