通过引用传递char

问题描述 投票:-1回答:1

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

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

我期待第二个输出是“打印此outc”

c pointers pass-by-reference
1个回答
1
投票

您将字符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.
© www.soinside.com 2019 - 2024. All rights reserved.