The problem is that I am trying to pass a sentence by reference to change something about it(this case adding a character), but nothing is changed.
The first thing I tried was this original code but without putting in any "*" or "&" and I got the same output. I have read other similar questions that have used strcpy() but I am not sure how that might apply to this problem or what the solution might be as I am unfamiliar with pointers used in this way.
char my_char_func(char *x)
{
return x+'c';
}
int main()
{
char (*foo)(char);
foo = &my_char_func;
char word[]="print this out";
puts(word);
foo(&word);
puts(word);
return 0;
}
I am expecting the second output to be "print this outc"
You're adding the character c to the actual pointer. As you can't dynamically expand your character array in C, I believe you're going to have to malloc a new array with space for the extra character, delete the pointer being passed in, and then set it the beginning of the new array. That should avoid memory overrun.
int main()
{
char (*foo)(char);
int i = 0;
foo = &my_char_func;
char word[]="print this out";
for(i = 0; i < size_of(word); ++i)
{
word[i] = toupper(word[i]);
}
puts(word);
foo(&word);
puts(word);
return 0;
}
If you don't want to use toUpper, you can change you function in either of two ways:
Option 1:
void my_char_func(char *string, int sizeOfString)
{
int i = 0;
for(i = 0; i < sizeOfString; ++i)
{
//Insert logic here for checking if character needs capitalization
string[i] = string[i] + ' ';
}
}
Option 2:
Do the same as with toUpper, simply calling your own function instead.