I'm having some trouble understanding pointers. In the following code, I'm trying print the address of a variable in 2 ways-once using the address operator and then using pointers:
#include<iostream>
using namespace std;
int main (void)
{
int x = 10;
int *int_pointer;
int_pointer = &x;
cout << "x address=" << &x << endl;
cout << "x address w pointer=" << int_pointer << endl;
return 0;
}
x address = 0028FCC4
x address w pointer = 0028FCC4
This works as expected. But when I do the same thing but now using character type variable, I get some trash output:
#include<iostream>
using namespace std;
int main(void)
{
char c = 'Q';
char *char_pointer;
char_pointer = &c;
cout << "address using address operator=" << &c << endl;
cout << "address pointed by pointer=" << char_pointer << endl;
return 0;
}
address using address operator=Q╠╠╠╠£åbªp é
address pointed by pointer=Q╠╠╠╠£åbªp é
I have no idea why this is happening. Thanks in Advance.
The C++ library overloads the << operator for certain types. (char*) is one of them. Cout is trying to print a string, an array of characters terminated by a null character.
Just cast the pointer:
cout << "address pointed by pointer" << ( void* )char_pointer << endl;
or
cout << "address pointed by pointer" << static_cast<void*>(char_pointer) << endl;
The reason it prints out junky stuff is because your char does not have a null terminator which means the program will keep searching for one until, and in the process will print out whatever it finds. The text you see is ASCII but referenced by the address which the ostream is misinterpreting. To get the address held in memory, you could use implicit conversion or a static_cast. I prefer the latter:
cout << "address pointed by pointer=" << static_Cast<void*>(char_pointer) << endl;
Like 2501 said, in different wording, &c, since c is a char, equals a char *, so it's going to try to print until the new line character '\0' that is either implicitly or explicitly put in character arrays going to std::cout so the stream knows where the end of the character array is.
So, yeah use the (void *) like 2501 said.
Related
#include <iostream>
using namespace std;
int main() {
int age = 20;
const char* pDept = "electronics";
cout << age << " " << pDept;
}
The above code is normal.
Why shouldn't I use cout << *pDept instead of cout << pDept above?
Both of them are legal in C++. Which one to use depends on what you want to print.
In your case, pDept is a pointer that points to a char in memory. It also can be used as a char[] terminated with \0. So std::cout << pDept; prints the string the pointer is pointing to.
*pDept is the content that pDept points to, which is the first character of the string. So std::cout << *pDept; prints the first character only.
This is not so much a question that I need solving, it's more a case of I made a mistake which resulted in weird output, and I'm curious what's going on.
So if point1 is a pointer to the char "var", and point2 is a pointer to the pointer point1, to correctly dereference point2 as follows:
cout << **point2 << endl;
Which would ouput "y" as expected.
However, if I incorrectly dereference the pointer, as follows:
cout << *point2 << endl;
Then the output would include any subsequent variables declared after the initial variable var.
For example, in the code below, var2 would also be included, for an ouput of "yn", and further variables such as
char var3 = 'a';
char var4 = 'b';
Also seem to be included for an ouput of "ynab".
I think I understand how it's happening, and outputting the memory addresses of each of the variables through a method such as:
cout << (void *) &var <<endl;
Which confirms that each variable is adjacent in memory, however I'm unsure why it is happening.
Why does improperly dereferencing a pointer to a pointer seem to return successive variables?
Code:
#include <stdio.h>
#include <iostream>
using namespace std;
char var = 'y';
char var2 = 'n';
//Declare point1 as a pointer to a char
char* point1 = &var;
//Declare point2 as pointer to pointer to char
char** point2 = &point1;
int main(int argc, char **argv)
{
cout << "Dereference point1: " << *point1 << endl;
cout << "Dereference point2: " << **point2 << endl;
cout << "Bad dereference of point2: " << *point2 << endl;
cout << "Var: " << var << endl;
return 0;
}
The expression *point2 is of type char * which is treated as a string. If it's not really a string then you have undefined behavior and that's really the end of the story.
In reality what happens is that the output operator << reads consecutive bytes from memory until it hits a zero (the "string terminator"). In your case the compiler have put the storage for the variables next to each other, that's why you see both being output in the "string".
C++ thinks that the pointer to char is the beginning of a string. So it tries to continue printing until it finds a NULL value.
When I run the following code:
int i[] = {1,2,3};
int* pointer = i;
cout << i << endl;
char c[] = {'a','b','c','\0'};
char* ptr = c;
cout << ptr << endl;
I get this output:
0x28ff1c
abc
Why does the int pointer return the address while the char pointer returns the actual content of the array?
This is due to overload of << operator. For char * it interprets it as null terminated C string. For int pointer, you just get the address.
The operator
cout <<
is overload 'char *' so it knows how to handle it (in this case, printing all chars till the end one).
But for int is not, so it just prints out the 'memory address'
A pointer to char is the same type as a string literal. So for the sake of simplicity, cout will print the content of the char array as if it was a string. So when you are doing this:
cout << "Some text" << endl;
It does not print the address, the same way as your code is doing.
If you want to pring the address, cast it to size_t
cout << reinterpret_cast<size_t>(ptr) << endl;
Why after using strdup(value) (int)value returns you different output than before?
How to get the same output?
My short example went bad, please use the long one:
Here the full code for tests:
#include <stdio.h>
#include <iostream>
int main()
{
//The First Part
char *c = "ARD-642564";
char *ca = "ARD-642564";
std::cout << c << std::endl;
std::cout << ca << std::endl;
//c and ca are equal
std::cout << (int)c << std::endl;
std::cout << (int)ca << std::endl;
//The Second Part
c = strdup("ARD-642564");
ca = strdup("ARD-642564");
std::cout << c << std::endl;
std::cout << ca << std::endl;
//c and ca are NOT equal Why?
std::cout << (int)c << std::endl;
std::cout << (int)ca << std::endl;
int x;
std::cin >> x;
}
Because an array decays to a pointer in your case, you are printing a pointer (ie, on non-exotic computers, a memory address). There is no guarantee that a pointer fits in an int.
In the first part of your code, c and ca don't have to be equal. Your compiler performs a sort of memory optimization (see here for a full answer).
In the second part, strdup allocates dynamically a string twice, such that the returned pointers are not equal. The compiler does not optimize these calls because he does not seem to control the definition of strdup.
In both cases, c and ca may not be equal.
"The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1." source
So it's quite understandable that the pointers differ.
I observe some weird behavior today , the code is as follow :
The Code :
#include <iostream>
struct text
{
char c;
};
int main(void)
{
text experim = {'b'};
char * Cptr = &(experim.c);
std::cout << "The Value \t: " << *Cptr << std::endl ;
std::cout << "The Address \t: " << Cptr << std::endl ; //Print weird stuff
std::cout << "\n\n";
*Cptr = 'z'; //Attempt to change the value
std::cout << "The New Value \t: " << *Cptr <<std::endl ;
std::cout << "The Address \t: " << Cptr << std::endl ; //Weird address again
return 0;
}
The Question :
1.) The only question I have is why cout theAddress for the above code would come out some weird value ?
2.)Why I can still change the value of the member c by dereferenncing the pointer which has weird address ?
Thank you.
Consider fixing the code like this:
std::cout << "The Address \t: " << (void *)Cptr << std::endl ;
There's a std::ostream& operator<< (std::ostream& out, const char* s ); that takes a char* so you have to cast to void* to print an address, not a string it "points" to
I think the "weird" stuff shows up because cout thinks it's a cstring, i.e. a 0-terminated character array, so it doesn't print the address as you expected. And since your "string" isn't 0-terminated, all it can do is walk the memory until it encounters a 0. To sum it up, you're not actually printing the address.
Why I can still change the value of the member c by dereferenncing the
pointer which has weird address
The address isn't weird, as explained above. In your code Cptr points to a valid memory location and you can do pretty much anything you want with it.