casting char ptr to int ptr...big number output

Why my value for *p is a huge number?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <stdio.h>

using namespace std;

int main () {

    char *aChar;
    char aCChar='A';
    aChar=&aCChar;
     int *p= (int *)aChar;
    printf ("%d, %u",p,*p);
    return 0;
}

A char is a single byte.

An int is four (or eight) bytes.

You are setting a char, and then you are telling your compiler to look at that memory address and pretend it is an int.

So we know what one of those four bytes in that int will be, because you set it yourself ('A'). What will the other three bytes be?
As already said, the printf reads sizeof(int) bytes from location that starts with the address of aCChar and interpretes those bytes as an integer. You have set bits of the first byte, but are those bits are even used for the same purpose in char and int types?

Undefined behaviour. That is what your program invokes and that is what you see.


More notes:

Why do you include both iostream and stdio.h even though you don't use anything from one of those headers?

Why do you include stdio.h? A C++ program should use cstdio instead. (A wrapper to same header.)

Why do you use C-style cast (int *)aChar? C++ has several forms of cast, each more precise than the C-style. See:
http://en.cppreference.com/w/cpp/language/static_cast
http://en.cppreference.com/w/cpp/language/reinterpret_cast
http://en.cppreference.com/w/cpp/language/explicit_cast

In addition to being more specific and thus avoiding some errors, it is easier to find C++-style casts from code, because "_cast" is a decent search word. The C-style cast lacks such uniqueness.
Thanks, :)

well I was looking at c code for printf but ya thought f using cstudio

thanks all...
Last edited on
Topic archived. No new replies allowed.