console outputs smiley face

2020-05-03 10:44发布

I have this code:

#include "stdafx.h"
#include <iostream>

typedef struct{
    int s1;
    int s2;
    char c1;
    char* arr;
}inner_struc;


int _tmain(int argc, _TCHAR* argv[])
{
    inner_struc myinner_struct;
    myinner_struct.s1 = myinner_struct.s2 = 3;
    myinner_struct.c1 = 'D';
    char arr[3] = {1,2,3};
    myinner_struct.arr = arr;

    std::cout << "first array element: " << myinner_struct.arr[1] << std::endl;
    return 0;
}

I wonder why am I getting a smiley face instead of the first array element! what am I doing wrong here? It compiles and runs fine however the output is

first array element: "smiley face"

What does this means? I am using Visual Studio 2010. Thanks

3条回答
▲ chillily
2楼-- · 2020-05-03 10:51

inner_struct.arr is declared as char *, which means it holds an array of characters (bytes). Do you want an array to hold the numbers 1, 2, 3? If so, use int. If you want letters, initialize the array with:

  char arr[3] = { 'a', 'b', 'c' };

KC

查看更多
虎瘦雄心在
3楼-- · 2020-05-03 11:05

You are outputing the second element in this array:

char arr[3] = {1,2,3};

You have assigned it the values 1 2 and 3, but the variable is of type char, so it is being interpreted as ascii. If you look up what character has a value of 2 on an ascii chart, you will see that it is a smily face. So it is indeed doing what you asked it to do.

http://mathbits.com/MathBits/CompSci/Introduction/ASCIIch.jpg

What are you expecting the output to be? if you wanted it to be a number, then you will have to add the character representation of that number into the array. ie in stead of 1, 2 or 3 use '1', '2', and '3'

查看更多
一纸荒年 Trace。
4楼-- · 2020-05-03 11:07

As far, as I can see, you are trying to output the first array element. But instead, you are printing the second one (the arrays are indexed starting from 0, not 1). The second element is 2. Now, please, take a look at this table, as you can see: the number 2 is a smiley face. The problem is that you are outputing a character with code 2, not '2'. In order to output a deuce, make your array look like this:

char arr[3] = {'1','2','3'};
查看更多
登录 后发表回答