通过函数传递字符串(C 编程)

Sha*_*ack 4 c string pointers function uppercase

我刚刚开始学习指针,经过大量添加和删除之后,*我将输入的字符串转换为大写的代码终于可以工作了..

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,在调用我发送的函数时word,它本身就是一个指针,那么char* upper(char *word)为什么我需要使用*word

它是指向指针的指针吗?另外,有char*没有因为它返回一个指向字符/字符串的指针?
请向我说明这是如何工作的。

cod*_*ing 5

那是因为您在这里需要的类型只是“指向 char 的指针”,表示为char *,星号 (*) 是参数类型规范的一部分。它不是“指向 char 的指针的指针”,可以写成char **

一些补充说明:

  1. 似乎您将取消引用运算符 *(用于访问指针指向的位置)与星号混淆为类型规范中的指针符号;您没有在代码中的任何地方使用取消引用运算符;您只是将星号用作类型规范的一部分!请参阅这些示例:要将变量声明为指向 char 的指针,您可以编写:

    char * a;
    
    Run Code Online (Sandbox Code Playgroud)

    a为指向的空间赋值(通过使用取消引用运算符),您可以编写:

    *a = 'c';
    
    Run Code Online (Sandbox Code Playgroud)
  2. 数组(char)不完全等于指针(指向char)(另请参见此处的问题)。但是,在大多数情况下,(char)数组可以转换为(char)指针。

  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.