Get up to 80 % extra points for free! More info:

Discussion: Typecasting an Array

In the previous quiz, C++ online test, we tested our experience gained from the course.

Activities
Avatar
Kiran Kumar
Member
Avatar
Kiran Kumar:1/17/2022 7:47

Hello, I just have a question on typecasting an array.
For the code below:

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char cbuff[32];
short * sbuff = ( short*) &cbuff;
sbuff[10] = 65;
cout << cbuff[20] ;
cin.get();
}

When I run on this online cpp compiler, the output is 'A'. However, shouldn't the typecasting change the arrays into pairs?
What I thought should happen was: since cbuff[20] and cbuff[21] are paired, when I initialize sbuff[10], the value should go into cbuff[21] first.

Can anyone explain to me what is going on?

 
Reply
1/17/2022 7:47
Avatar
Lokesh Joshi
Member
Avatar
Lokesh Joshi:4/19/2023 7:04
#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char cbuff[32];
    short* sbuff = reinterpret_cast<short*>(&cbuff[0]); // use reinterpret_cast for type punning

    sbuff[10] = 65;
    cout << static_cast<int>(cbuff[20]); // cast the char to an int to print it correctly
    cin.get();
    return 0;
}

Try this, hope this will help you, or you can choose a different compiler to run the code. I found this post on the internet; here author listed many cpp compiler, choose any online compiler and run the code.

 
Up Reply
4/19/2023 7:04
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.