问题是我试图通过引用传递一个句子来更改它的某些内容(本例添加一个字符),但没有任何改变。
我尝试的第一件事是这个原始代码,但没有输入任何“*”或“&”,我得到了相同的输出。我读过其他使用 strcpy() 的类似问题,但我不确定这如何适用于这个问题,或者解决方案可能是什么,因为我不熟悉以这种方式使用的指针。
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;
}
我期望第二个输出是“打印此输出”
最佳答案
您正在将字符 c 添加到实际指针中。由于您无法在 C 中动态扩展字符数组,因此我相信您必须为额外字符分配一个带有空间的新数组,删除传入的指针,然后将其设置为新数组的开头。这应该可以避免内存溢出。
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.
关于c - 通过引用传递 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55408953/