user3552483
user3552483

Reputation: 1

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 " ???????????????????

Upvotes: 0

Views: 89

Answers (2)

Rogiel Sulzbach
Rogiel Sulzbach

Reputation: 318

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.

Upvotes: 2

Blaz Bratanic
Blaz Bratanic

Reputation: 2279

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

Upvotes: 0

Related Questions