Shubham Yadav
Shubham Yadav

Reputation: 591

Converting int value to char pointer difference in C and C++

I wrote the following code to convert int value to char pointer and this works in C.

int i = 54;
char *ii;
ii = &i;
printf("%d\n", *ii);

The output is:

54

While when I write the same in C++, it doesn't work.

int i = 54;
char *ii;
ii =  (char *)&i;
cout<<*ii;

The output is:

6

Can someone please explain why this happens and how shall I get it working in C++.

Thanks in advance.

Upvotes: 0

Views: 1957

Answers (2)

Pete Becker
Pete Becker

Reputation: 76235

Different isn't the same. Try this:

#include <cstdio>
#include <iostream>

int main() {
    int i = '6';
    char *ii = reinterpret_cast<char*>(&i);
    std::printf("%c\n", *ii);
    std::printf("%d\n", *ii);
    std::cout << *ii << '\n';
    std::cout << (int)*ii << '\n';
}

Initializing i to '6' is just a clarification.

In the calls to printf, the char value that *ii points to is promoted to int in the function call. Types smaller than int get promoted when they're arguments to the variable part of a function that takes a variable parameter list (such as printf).

The first printf statement prints the value of *ii as a character value; you'll get "6". The second prints it as an integer value; you'll get whatever value represents the character '6' (in ASCII that's 54, which is probably what you'll see).

The first insertion into std::cout inserts the char value; stream inserters are overloaded for integral types, so you get the inserter that takes an argument of type char, and it displays the character that the value represents, just like the first printf call.

The second insertion into std::cout inserts the integer value of *ii, just like the second call to printf.

Upvotes: 1

dbush
dbush

Reputation: 223689

When you call printf like this:

printf("%d\n", *ii);

The %d format specifier means that the given int argument will be printed as an int. Even though what you pass is a char, because printf is a variadic function it is promoted to an int, so it matches the format specifier.

When you output using cout:

cout<<*ii;

The << operator has an overload for a char. Since the right side has type char, that's the overload that is used. That particular instance of << prints the argument as a char. Since the ASCII code 54 corresponds to the character '6', that's what gets printed.

You'll get the opposite results if you use %c in the printf format, and if you cast *ii to int in the cout call.

Upvotes: 2

Related Questions