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

标签 c arrays pointers c-strings memory-address

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);

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

最佳答案

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

关于c - 'char *' 和 'char (*) [100]' 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60690774/

相关文章:

arrays - 在数字序列的末尾查找重复序列

c - 将动态创建的结构体作为非指针对象返回

c++ - 为什么获取成员函数的地址需要 & 运算符而不是全局函数?

C如何将用户输入的单词存储在字符指针中

c - 创建自定义 gsource 时如何使用串行引脚?

c - 蛮力算法的优化还是替代?

c++ - 您如何测试您的计算机每秒可以执行多少条指令?

CS50 PSet 1 贪婪

将指针的结构信息转换为数组

python - 优化三个数组上的现有 for 循环