Consider this function that adds up some elements of an array and then the sampl
ID: 3535224 • Letter: C
Question
Consider this function that adds up some elements of an array and then the sample calls to the right.
cout << sum(a10,10);
cout << sum(a20,10);
cout << sum(a20+10,10);
cout << sum(a10,20);
What pre-condition does this sum function have that is being violated?
Is there any way for this function to verify this pre-condition itself?
int sum( int *p, int elements )
{
int total = 0;
while (elements > 0)
{
total += *p;
elements--;
p++;
}
}
int a10[10],a20[20];
cout << sum(a10,10);
cout << sum(a20,10);
cout << sum(a20+10,10);
cout << sum(a10,20);
Explanation / Answer
cout << sum(a20+10,10); this function call will fail as the array when passed as parameter with address seperate , it will have problem analysing this.