将字符串传递给函数(C编程)

4

我刚开始学习指针,经过很多次添加和删除 *,我编写的将输入的字符串转换为大写的代码终于成功了。

#include <stdio.h>
char* upper(char *word);
int main()
{
    char word[100];
    printf("Enter a string: ");
    gets(word);
    printf("\nThe uppercase equivalent is: %s\n",upper(word));
    return 0;
}

char* upper(char *word)
{
    int i;
    for (i=0;i<strlen(word);i++) word[i]=(word[i]>96&&word[i]<123)?word[i]-32:word[i];
    return word;
}

我的问题是,在调用我发送的函数时,我发送了一个指针word,那么在char* upper(char *word)中,为什么需要使用*word?这是指向指针的指针吗?此外,char*是否存在是因为它返回指向字符/字符串的指针呢?请向我说明其工作原理。

我不确定你在问什么。你是在问为什么是 upper(char *word),而不是 upper(char word) 吗? - Corbin
函数upper要求一个指针作为参数,而你提供了一个指针(word)。据我所知,这是正确的方式。 - Marnix v. R.
为了消除混淆,请将代码中的 word 参数更改为 upper 或本地变量 word 的名称。 - Mat
为什么不在循环中使用 toupper 函数? - Some programmer dude
@Shashwat Mehta:如果您发现某个答案有帮助,请记得接受它。 - codeling
3个回答

5
这是因为您需要的类型仅为“指向字符”的指针,表示为char *,星号(*)是参数类型规范的一部分。它不是“指向指向字符的指针”,这应写作char **
一些额外的备注:
  1. It seems you're confusing the dereference operator * (used to access the place where a pointer points to) with the asterisk as a pointer sign in type specifcations; you're not using a dereference operator anywhere in your code; you're only using the asterisk as part of the type specification! See these examples: to declare variable as a pointer to char, you'd write:

    char * a;
    

    To assign a value to the space where a is pointing to (by using the dereference operator), you'd write:

    *a = 'c';
    
  2. An array (of char) is not exactly equal to a pointer (to char) (see also the question here). However, in most cases, an array (of char) can be converted to a (char) pointer.

  3. Your function actually changes the outer char array (and passes back a pointer to it); not only will the uppercase of what was entered be printed by printf, but also the variable word of the main function will be modified so that it holds the uppercase of the entered word. Take good care the such a side-effect is actually what you want. If you don't want the function to be able to modify the outside variable, you could write char* upper(char const *word) - but then you'd have to change your function definition as well, so that it doesn't directly modify the word variable, otherwise the Compiler will complain.


3

char upper(char c) 是一个函数,接受一个字符并返回一个字符。如果你想要使用字符串,则约定字符串是以空字符结尾的字符序列。你不能将完整的字符串传递给函数,因此需要传递第一个字符的指针,因此有char *upper(char *s)。指向指针的指针会有两个星号,例如 char **pp:

char *str = "my string";
char **ptr_to_ptr = &str;
char c = **ptr_ptr_ptr; // same as *str, same as str[0], 'm'

upper函数也可以实现为void upper(char *str),但是让upper返回传递的字符串更加方便。在您的示例中,当您printf通过upper返回的字符串时,就利用了这一点。

顺带一提,您可以优化您的upper函数。您正在为每个i调用strlen。C字符串始终以空字符结尾,因此您可以将i < strlen(word)替换为word[i] != '\0'(或word[i] != 0)。另外,如果您检查并计算'a'、'z'、'A'、'Z'或其他您想要的字符,而不是与96和123进行比较并减去32,那么代码的可读性会更好。


0

尽管指针和函数中的数组单词是指向同一物体的指针,但在传递参数时只是传递了“指向物”的副本,即输入的单词被传递并且对指针单词进行的任何操作都是在其上进行的,因此最终我们必须返回一个指针,因此返回类型被指定为*。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接