【问题标题】:What is the difference between 'char *' and 'char (*) [100]'?'char *' 和 'char (*) [100]' 有什么区别?
【发布时间】:2020-06-26 16:02:35
【问题描述】:
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 是单个字符,char[100] 是 100 个字符的块。这些是不同的类型,因此指向每个的指针是不同类型的指针。您将函数设计为期望指向单个字符的指针
  • 你应该使用toLowerCase(word)
  • word 已经表示一个指针;即char *。您可以在不使用引用运算符&amp; 的情况下传递它。对于char *p = "some text";p 指向字符串的起始地址,而&amp;p 表示指针变量的地址(一个char **),而不是它指向的地址。
  • @M.M char 是单个字符,char[100] 是 100 个字符的块。这些是不同的类型-> 同意,因此指向每个的指针是不同类型的指针?您将函数设计为期望指向单个字符的指针?
  • @WeatherVane 这对我的问题有何影响?我问的是完全不同的事情

标签: c arrays pointers c-strings memory-address


【解决方案1】:

char x[100]

数组x衰减为指针:

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

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

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

所有这些指针都引用数组的相同开头,只有类型不同。类型很重要!!

您不应将 &amp;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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-03
    • 2010-12-14
    • 2012-08-14
    • 2010-10-27
    • 2014-03-21
    相关资源
    最近更新 更多