'char *' 和 'char (*) [100]' 有什么区别?

3
int main()
{
    char word[100];
    char* lowerCase;

    scanf("%s", word);

    lowerCase = toLowerCase(&word);
    printf("%s", lowerCase);
}

char * toLowerCase(char *str)
{
    int i;

    for(i = 0; str[i] != '\0'; ++i)
    {
        if((str[i] >= 'A') && (str[i] <= 'Z'))
        {
            str[i] = str[i] + 32;
        }
    }

    return str;
}

在执行以上代码时,我收到了一个警告。 警告信息如下:

try.c: In function 'main':
try.c:16:26: warning: passing argument 1 of 'toLowerCase' from incompatible pointer type [-Wincompatible-pointer-types]
  lowerCase = toLowerCase(&word);
                          ^~~~~
try.c:4:7: note: expected 'char *' but argument is of type 'char (*)[100]'
 char* toLowerCase(char *str);

我无法理解为什么会出现这个警告?当我把(word)传递给函数时,没有警告,但是当我执行以下代码时输出结果相同:

printf("%d", word);
printf("%d", &word);

如果地址相同,那么为什么会有这个警告?

4
char是单个字符,char[100]是由100个字符组成的块。它们是不同的类型,因此每个类型的指针也是不同的。您设计的函数期望一个指向单个字符的指针。 - M.M
1
你应该使用 toLowerCase(word) - Sulthan
word 已经表示一个指针,即 char *。您可以在不使用引用运算符 & 的情况下传递它。对于 char *p = "some text";p 指向字符串的起始地址,而 &p 表示指针变量(一个 char **)的地址,而不是它所指向的地址。 - ssd
这就是为什么要求您发布最小可重现示例,以展示完整的代码。然后读者就知道您有一个函数原型,并且与函数定义匹配。 - Weather Vane
@P__J__的回答讲解得很好。然而,这个问题是相关的,并提供了有关数组参数类型的更多见解:https://dev59.com/GWw15IYBdhLWcg3wfsBy#51527502 - Gabriel Staples
显示剩余4条评论
1个回答

4

char x[100]

数组 x 会衰变为指针:

x - 指向字符的指针 (char *)

&x - 指向100个字符数组的指针 (char (*)[100]);

&x[0] - 指向字符的指针 (char *)

所有这些指针都引用数组的同一开始,仅类型不同。类型很重要!

您不应将 &x 传递给期望 (char *) 参数的函数。

为什么类型很重要?:

char x[100];

int main()
{
    printf("Address of x is %p, \t x + 1 - %p\t. The difference in bytes %zu\n", (void *)(x), (void *)(x + 1), (char *)(x + 1) - (char *)(x));
    printf("Address of &x is %p, \t &x + 1 - %p\t. The difference in bytes %zu\n", (void *)(&x), (void *)(&x + 1), (char *)(&x + 1) - (char *)(&x));
    printf("Address of &x[0] is %p, \t &x[0] + 1 - %p\t. The difference in bytes %zu\n", (void *)(&x[0]), (void *)(&x[0] + 1), (char *)(&x[0] + 1) - (char *)(&x[0]));
}

结果:

Address of x is 0x601060,    x + 1 - 0x601061   . The difference in bytes 1
Address of &x is 0x601060,   &x + 1 - 0x6010c4  . The difference in bytes 100
Address of &x[0] is 0x601060,    &x[0] + 1 - 0x601061   . The difference in bytes 1

https://godbolt.org/z/SLJ6xn


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