简体   繁体   中英

What is the difference between 'char *' and 'char (*) [100]'?

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

I am getting a warning while executing the above code. the warning is

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

I am not able to understand why this warning is coming? if i am passing (word) to the function there is no warning, but when i execute the following code the output is same:

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

If the address is same then why this warning?

char x[100]

Array x decays to pointer:

x - pointer to the char ( char * )

&x - pointer to a the array of 100 chars ( char (*)[100] );

&x[0] - pointer to the char ( char * )

all of those pointers reference the same start of the array, only the type is different . The type matters!!.

You should not pass the &x to the functions which expect ( char * ) parameters.

Why type matters?:

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

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM