通过引用传递字符

Passing char by reference

问题是我试图通过引用传递一个句子来改变它的一些东西(在这种情况下添加一个字符),但没有任何改变。

我首先尝试的是这个原始代码,但没有输入任何“*”或“&”,我得到了相同的输出。我读过其他使用过 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;
}

我希望第二个输出是 "print this outc"

您正在将字符 c 添加到实际指针。因为你不能在 C 中动态扩展你的字符数组,我相信你将不得不为额外的字符分配一个带有 space 的新数组,删除传入的指针,然后将其设置为开头的新阵列。那应该避免内存溢出。

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.