I'm learning C++ on my own and am reading the book "C++ Crash Course" which has the following exercise:
3-2. Add a read_from and a write_to function to Listing 3-6. These functions should read or write to upper or lower as appropriate. Perform bounds checking to prevent buffer overflows.
Listing 3-6 that it references looks like this:
#include <cstdio>
int main(){
char lower[] = "abc?e";
char upper[] = "ABC?E";
char* upper_ptr = upper;
lower[3] = 'd';
upper_ptr[3] = 'D';
char letter_d = lower[3];
char letter_D = upper_ptr[3];
printf("lower: %s\nupper: %s\n", lower, upper);
}
The way I rewrote it is this:
char* write_to(char string[], int index, char replacement){
if (sizeof(string) <= index){
string[index] = replacement;
return string;
}
return NULL;
};
char read_from(char string[], int index){
if (sizeof(string) <= index){
return string[index];
}
return NULL;
};
int main(){
char lower[] = "abc?e";
char upper[] = "ABC?E";
char* upper_ptr = upper;
lower[3] = 'd';
upper_ptr[3] = 'D';
char letter_d = lower[3];
char letter_D = upper_ptr[3];
printf("lower: %s\nupper: %s\n", lower, upper);
char* changed_lower[] = {write_to(lower, 3, 's')};
printf("changed lower: %s\nindex 3 of upper: %s\n",
changed_lower, read_from(upper, 3));
The program runs, but gives me some warnings and the wrong outcome:
lower: abcde
upper: ABCDE
changed lower:
index 3 of upper: (null)
I think the program should return something more like:
lower: abcde
upper: ABCDE
changed lower: abcse
index 3 of upper: D
Where am I going wrong?
Edit: I removed the warnings because people were hyper-fixating on those and not the real problem, which is that it doesn't give me the correct output.