adress of different types

the code is
1
2
3
4
5
6
7
8
9
10
11
#include<iostream> 
using namespace std; 
int main() 
{
    char ch='a', c='s';
    int i=12;
    double f=1.2;
    cout << &i << "\t" << &f << "\t" << &ch
        << "\t" << &c << endl;
    return 0;
}


output:
0x22ff70 0x22ff68 a?"" sa?""

why the address of char is different from others, i mean, for example, ch='a',
and it's address is
a...
, and variable c's address is
s...
Last edited on
the address of a char is a pointer to that char. this is interpreted as a C string and the output will show all the bytes in memory until a '\0' is found.
This allows this thing:
1
2
char *cstr = "hello world";
cout << cstr;


You can cast &c to a void* to solve your problem
I don't think I quite understand what you're asking, so I'll answer what I assume it is you're asking.

Stack allocation works by "pushing" variables onto a stack. The bottom of the stack (where the first pushed variables are) is higher in memory than the top, which mean the stack grows downwards.
The stack in your case looks somewhat like this:
<- lower memory higher memory ->
[double f][int i][char c][char ch]
As you can see, it's not the type of the variables that determines the memory address of a variable, but the order in which the variables are declared.
If you had written
1
2
3
int i=12;
double f=1.2;
char c='s',ch='a';
the stack would have looked like this:
<- lower memory higher memory ->
[char ch][char c][double f][int i]

Variable declarations aren't the only things pushed onto the stack. Function calls are also pushed onto it.
Last edited on
Topic archived. No new replies allowed.