i have tested two different varianat of similary code ,suppose i have char array
char x[]="snow comes in winter ";
then following code
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char x[]="snow comes in winter ";
int k=0;
int n=3;
cout<<x+n-k+1<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
prints "comes in winter "
while following
#include <iostream>
#include <string.h>
using namespace std;
int main(){
//char x[]="snow comes in winter ";
int a[]={12,3,2,4,5,6,7};
int k=0;
int n=3;
cout<<a+n-k+1<<endl;
return 0;
}
prints 0xbffd293c
if we change it a bit
#include <iostream>
#include <string.h>
using namespace std;
int main(){
//char x[]="snow comes in winter ";
int a[]={12,3,2,4,5,6,7};
int k=0;
int n=3;
cout<<*(a+n-k+1)<<endl;
return 0;
}
prints number 5.
so my question is why we can access in case of char array so easily?what is main reason of it?i am very curiousy and please could anybody explain me?
Because there’s a convention that C strings are represented by
char*, people assumechar*are actually strings. Theiostreams follow that and overload output forchar*to print the string, whereas for anint*(in your second example), they print the representation of the address.BTW there is a similar overload for input, which is most unfortunate, since you can’t control that to prevent buffer overflows. ie. don’t do this: