In: Computer Science
The following code segment which uses pointers may contain logic and syntax errors. Find and correct them.
a) Returns the sum of all the elements in summands
int sum(int* values)
{
int sum = 0;
for (int i = 0; i < sizeof(values); i++)
sum += *(values + i);
return sum;
}
b) Overwrites an input string src with "61C is awesome!" if there's room. Does nothing if there is not. Assume that length correctly represents the length of src.
void cs61c(char* src, size_t length) {
char *srcptr, replaceptr;
char replacement[16] = "61C is awesome!";
srcptr = src;
replaceptr = replacement;
if (length >= 16) {
for (int i = 0; i < 16; i++)
*srcptr++ = *replaceptr++;
}
}
1)
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
#include <stdio.h>
// We can't find the size of the array from a function.
// We have to pass the size as a parameter to the function.
int sum(int* values,int size)
{
int sum = 0;
//use the size variable here
for (int i = 0; i < size; i++)
sum += *(values + i);
return sum;
}
//testing the sum() function
int main() {
int values[5]={1,2,3,4,5};
int size = sizeof(values) / sizeof(values[0]);
printf("%d",sum(values,size));
return 0;
}
====================
2)
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
#include <stdio.h>
void cs61c(char* src, size_t length)
{
//change *replaceptr here
char *srcptr, *replaceptr;
char replacement[16] = "61C is awesome!";
srcptr = src;
replaceptr = replacement;
if (length >= 16)
{
for (int i = 0; i < 16; i++)
{
*srcptr++ = *(replaceptr)++;
}
}
}
//testing the function.
int main() {
char src[] = "PraveenKumarREDDYkumar";
cs61c(src,24);
printf("%s",src);
return 0;
}
-================