Interview Question
Country: United States
I think these days compiler does the optimization while compiling.
#include <iostream>
int main()
{
char * p="i am the one";
char * q="i am the one";
if (p==q)
std::cout << "Pointer has same address";
else
std::cout << "Pointer has same Different address";
}
result is "Pointer has same address".
No they are not equal. The content at the location are equal but as such they are actually two distinct strings in different memory locations.
so , that means statement ------> if(p==c)
returns false ??? or
p==c ----->compares the string ???
ya. the p==c compares the values at the location itself.
however when you print &p and &c you will notice that the values are different indicating that their addresses are different
when you do &p and &c ...it 's just the values of these variable p & q , not the address they are pointing to ..... what i think is both pointer's are holding same address . whenever string literals assigned to pointers ...it's stored in a read only memory of data segment and nobody can change this value.. so the same string assigned to other pointer store the same address.
Well the pointers are equal because they both are pointing to the same string. The above code can also be written as
char *p = "hello";
char * q = p;
Now this is clear that both p and q are "equal". But they both are at different memory locations and there address would be different. This is because the same memory location cannot be allocated to two members.
In C,C++,JAVA, strings are immutable (not d array of characters). This means a string once created cannot be modified. Only flushing d buffer can remove it. Next point is when a string is created it is stored in buffer. Next time again when new string is created, it checked whether it is present in buffer or not?? if present tht address is assigned, otherwise new address stores new string n this new address is assigned. Hope tht helps
String literals are stored in the read-only area of the data segment. So it makes no sense to make 2 different copies of the same string, as u cannot edit them anyway. Hence, these two pointers will point to the same location in memory.
You can always assign different values to the pointers, but you cannot change the value.
e.g. you cannot do p[2]='a';
Yes these two pointers are equal , check the address of pointers with &p value after typecasting char pointer to void *...
- kk July 05, 2012