简体   繁体   中英

c++ pointers and string of characters

am a bit confused about something in string of characters and pointers regarding c++ language ..

well, i came to know that a name of an array of characters is actually the address of it's first element and i also know that The cout object assumes that the address of a char is the address of a string, so it prints the character at that address and then continues printing characters until it runs into the null character (\\0).

but here is the interesting part i tried this code in codeblocks

char arr[10]="bear";    
cout <<&arr<<endl;  // trying to find the address of the whole string 
cout<<(int *)arr<<endl; // another way of finding the address of the string 
cout<<(int *)arr[0]<<endl;  // trying to find the address of the first element 

what came on the screen was as follows

0x22fef6, 0x22fef6, (0x62) <<<< My question is , what the heck is that? .. If the arrayname holds the address of the first element , shouldn't the first element address be " 0x22fef6 " ???????????????????

The [] operator does not return an address but dereferences the pointer at the given offset.

You could write an equivalent to the [] operator as follows:

char arr[10] = "bear";
char c = *(arr+0); // == arr[0] == 'b'

That is, you take the pointer arr , increase it by 0 char and then dereferences it to get it's value.

char arr[10]="bear";    
cout <<&arr<<endl;
cout<<(int *)arr<<endl;
cout<<(int *)(arr+0)<<endl; // increases the address by 0
cout<<(int *)(&arr[0])<<endl; // the address of the value at index 0

This would do what you have expected it to do.

arr[0] equals *(arr + 0) ; you dereference the pointer and obtain the value it holds. To get what you want you need to reference the element, like &arr[0] .

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