Interview Question
Dev Leads Dev LeadsCountry: India
Interview Type: In-Person
P is defined as constant so no guaranteed behavior of p++. In fact I am not sure if it will compile as you are attempting to modify value of a constant
Hey, do u know what is constant...what u thinking is totally wrong....
const char* p = "Test"; here data is const not the pointer so *p = 'A' //error
p++; // no issue
char const *p = "Test"; //this and above are same thing const u putting after * or before * makes sensde
char const * p is same as const char *p
the logic was here string literals stored in RO data section so this will available even after stack become empty so this programme prints "This is test string";
char arr[] = "This is test string"; if i do like this then its char *const arr= "This is test string";
in this case if i try ptr++ it fail
so we do like
int i = 0;
while(*(arr+i) != '\0')
{
cout<<*(arr+i);
i++;
}
but u can change data here not the pointer.....
char* const fun()
{
char arr[] = "This is test string";
return arr;
}
this is wrong thing once stack empty data lost and if u try access it u get seg fault...
Yes while( *p != '\0') it should be i write ! mistakely
now i modify fun
const char * fun()
{
return "This is test string";
}
is there any issue ....
there is no issue string literals go in data section so without pointing to a variable we can directly return them....
nothing will display because of the loop
while(!p!='\0')
the associativity of ! operator is Right to left due to this (p!='\0') will execute first and give True than !True become False than the control will not come inside the loop. if it come inside the loop than generate an error, because the string "This is test string" do not have the NULL at last and the loop will never end
while(!p!='\0') nothing will display
while(*p !='\0') will generate error because the loop never end
The program will compile but the output will be empty. If you will replace !p with *p in while loop then it will give you the correct result. Otherwise !p means that the address that is assigned to p we apply a not operator that is if p is 0 only then !p is true and then the loop will execute. If you replace !p with p then the output will be an infinite set of characters as the '\0' is not defined to be any valid address.
P is defined as constant so no guaranteed behavior of p++. In fact I am not sure if it will compile as you are attempting to modify value of a constant
- Anonymous June 11, 2014