简体   繁体   English

小型C ++代码激怒了我

[英]Small C++ code irritating my mind

please consider this short C++ code 请考虑这段简短的C ++代码

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

void main()
{
    clrscr();
    char arr[]="MQMHSJKLSUGDUGIGIUDKLKO";
    for(int i=0;i<5;i++)
    {
       if(i%2==0)
       {
           cout<<arr[i];
       }
    }

    char a[]={'78','45','21','5'};
    cout<<(int)a;
    getch();
}

the output is 'MMS 18' 输出为“ MMS 18”

MMS is clear from the first loop, but how '18' is the output of second one ? 从第一个循环中可以清楚地看到MMS,但是第二个循环的输出如何为“ 18”? even if you change the array elements, the answer remains 18. Please explain ! 即使更改数组元素,答案仍然为18。请解释!

a converted to a pointer to its first element. a转换成一个指向它的第一个元素。 You are trying to print the address of first element by casting it to int . 您正在尝试通过将第一个元素的地址强制转换为int来打印地址。 Result may vary compiler to compiler. 结果可能因编译器而异。

'a' represent the address of the first element in the array. “ a”代表数组中第一个元素的地址。
As if in your code the address of the first element of the array 'a' is 18.If you try *a instead of a it would give you the answer as 78.The code you expect could be 就像在您的代码中,数组'a'的第一个元素的地址是18如果尝试使用* a而不是a,它将给出78的答案。您期望的代码可能是

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
    clrscr();
    char arr[]="MQMHSJKLSUGDUGIGIUDKLKO";
    for(int i=0;i<5;i++)
    {
        if(i%2==0)
        {
           cout<<arr[i];
        }
    }

    char a[]={'78','45','21','5'};
    cout<<(*a);
    getch();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM