Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading