reference derefrence

what is wrong here ?
as ted will store address of char c that is an int.
then why its giving error in line-- 'ted=&c;'

#include <iostream>

using namespace std;

int main()
{
int ted;
char c='d';
ted=&c;
cout<<*ted<<endl;
return 0;
}
Last edited on
ted is not a pointer. So this statement

ted=&c;

is incorrect.
This is the correct way to do it:

1
2
3
4
char* ted;
char c = 'd';
ted = &c;
cout << *ted << endl;

ted needs to be a pointer to a char.
Last edited on
Try the following


#include <iostream>

using namespace std;

int main()
{
int ted;
char c='d';
ted = reinterpret_cast<int>( &c );
cout<<*reinterpret_cast<char *>( ted )<<endl;
return 0;
}
but when i store address of any integer in ted say
int i;
ted=&i;
that works fine!
i have doubt in that part that work of ted to store address of any value that address is definitely integer
then why it is giving error when i am storing address of char?
The address of something is not guaranteed to fit inside an integer. It just happened to work for you because on your compiler that's how it works. It is not standard though so you can't do it.
it will work for any compiler
in c and cpp size of pointer is always as equal to size of int
i am very sure about that part!
No, that is not how it works:
http://stackoverflow.com/a/4574870/1959975
L B has told you everything there is to; you got lucky that your computer is behaving this way. Moreover, recall that integers are usually stored in four bytes of memory whereas a character is stored in one.
if what you are saying is right than i have stored address in integer pointer that's size is greater than char
than it should be able to store the address of char as size of int is greater than size of char ?"
A char is *almost* always going to be smaller than an int.

This forum is primarily English, by the way.
Topic archived. No new replies allowed.