c - 通过引用传递 char

标签 c pointers pass-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;
}

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

最佳答案

您正在将字符 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/

相关文章:

c - 用于 Linux 的 C 语言示例 NPAPI 插件

swift - 如何将 Unmanaged<CFTypeRef> 转换为 Swift 3

c++ - 指向 vector 的指针只返回 vector 的最后一个值

c - 是否可以在没有特定数据类型的情况下在 C 中创建指针

jquery - 如何将 DOM 对象的引用传递给 jQuery 函数?

php - Laravel 通过引用事件订阅者传递数组

c - 为什么我会收到错误 "Segmentation fault (core dumped)"?

c - 了解 C 中的位级浮点乘法?

c - 在 C 中修改函数内的 char 数组

C++:合并排序问题:超出范围?