Search code examples
c++arrayspointersimplicit-conversionstring-literals

Why do the two pointer arrays return different addresses?


In the following code, I thought that the two outputs were the same. But in fact they are not! In my computer, the first output is 0x6ffde0, while the latter output is 0x6ffdb0.

#include<iostream>
using namespace std;

int main(){
    const char *s[] = {"flower","flow","flight"};
    char *s1[] = { (char*)"flower",(char*)"flow",(char*)"flight" };
    cout << s<< endl; // 0x6ffde0
    cout << s1<< endl; // 0x6ffdb0
    return 0;
}

I tried to output the address of "flower" and (char*)"flower". The results are the same.

cout<<(int *)"flower"<<endl; // 0x488010
cout<<(int *)(char*)"flower"<<endl;// 0x488010

Can anyone explain this problem please?


Solution

  • Array designators used in expressions with rare exceptions are implicitly converted to pointers to their first elements.

    As these two arrays

    const char *s[] = {"flower","flow","flight"};
    char *s1[] = { (char*)"flower",(char*)"flow",(char*)"flight" };
    

    occupy different extents of memory then the addresses of their first elements are different.

    In fact these two statements

    cout << s<< endl; // 0x6ffde0
    cout << s1<< endl; // 0x6ffdb0
    

    are equivalent to

    cout << &s[0]<< endl; // 0x6ffde0
    cout << &s1[0]<< endl; // 0x6ffdb0
    

    As for string literals as for example "flower" then it is in turn an array of the type const char[7] and occupies its own extent of memory. That is these three arrays s, s1, and "flower" occupy different extents of memory.