简体   繁体   中英

What's the difference between a+i and a[i]

I try to use a two dimensional character array to store strings,and then I want to use the function strcmp to compare two adjacent strings.

Here is the code,it is a successful one.

#include<stdio.h>
#include<string.h>
int main()
{
    char a[20][20];
    for(int i=0;i<20;i++)
        scanf("%s",a[i]);//input
    for(int i=1;i<20;i++)
    {
        if(strcmp(a[i],a[i-1])>0)//compare
        {
            //do something here
        }
    }
    return 0;
}

When i try to use a+i to subsitute a[i] ,the problem occurs.(I'm a beginner of pointer and in my mind these two expressions are the same)

The second code is the following one.

#include<stdio.h>
#include<string.h>
int main()
{
    char a[20][20];
    for(int i=0;i<20;i++)
        scanf("%s",a+i);//input
    for(int i=1;i<20;i++)
    {
        if(strcmp(a+i,a+i-1)>0)//compare
        {
            //do something here
        }
    }
    return 0;
}

The Compiler tells me that there is an error in the line if(strcmp(a+i,a+i-1)>0)//compare with the following message.

[Error] cannot convert 'char (*)[20]' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'

I'm quite confused of this problem. However, if I just use a+i for the input part, it works well.So i want to konw the difference between a+i and a[i] and why a+i can't serve as the argument for strcmp but it can work in scanf .

Thanks.

Short answer: a[i] resolves to *(a+i) . Mind the star "*".

Long answer: at semantic level, a[i] is meant to access to element i of array a . This is internally done by finding out the address of a 's beginning in memory, then adding i times the size of an element to it to find the place of targeted element.

Aside from this, invoking a (an array name) alone is resolved into this array's address, thus into a pointer-typed expression. Moreover, "pointer arithmetics" states, when combining both integer and pointer values, the increment is the size of pointed element. Therefore, if you're pointing for instance a 32-bits integer at a=0x80000000 , a+1 will be 0x80000004 .

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