Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine sizeof string and chararcter

Tags:

c++

sizeof

The last 2 cout statements have the same size. why?

int main() 
{
char ch=127;
cout<<sizeof(ch)<<endl;    //Size=1
cout<<sizeof("Hello")<<endl;    //Size=6
cout<<sizeof("Hello"+ch)<<endl;    //Size=8
cout<<sizeof("HelloWorld"+ch)<<endl;    //Size=8
return 0;
}

Please explain. Thanks

like image 712
Rohan Saxena Avatar asked Jan 26 '23 07:01

Rohan Saxena


1 Answers

When you do "Hello"+ch the array containing the string "Hello" decays to a pointer to its first element, and you add ch to this pointer.

The result of pointer arithmetic is a pointer, which is what you get the size of.


Equivalent code would be something like

char const hello[] = "Hello";
char const* phello = hello;  // equivalent to &hello[0]
char const* result = phello + ch;
cout << sizeof(result) << endl;
like image 171
Some programmer dude Avatar answered Feb 07 '23 15:02

Some programmer dude