sizeof操作符返回C和不同的价值观; C ++? [英] sizeof operator returns different values for c & c++?

查看:111
本文介绍了sizeof操作符返回C和不同的价值观; C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个字符数组是全局定义和名称相同的结构,在函数中定义。为什么sizeof操作符返回C和不同的价值观; C ++?

A character array is defined globally and a structure with same name is defined within a function. Why sizeof operator returns different values for c & c++ ?

char S[13];
void fun()
{
    struct S
    {
        int v;
    };
    int v1 = sizeof(S);
}

//返回4 C ++和13用C

// returns 4 in C++ and 13 in C

推荐答案

由于在C ++中,结构您定义被命名为取值,而在C,它的命名的struct (这就是为什么你经常看到使用 typedef结构 C code)。如果你到code更改为以下,你会得到预期的结果:

Because in C++, the struct you defined is named S, while in C, it's named struct S (which is why you often see typedef struct used in C code). If you were to change the code to the following, you would get the expected results:

char S[13];
void fun()
{
    typedef struct tagS
    {
        int v;
    } S;
    int v1 = sizeof(S);
}

这篇关于sizeof操作符返回C和不同的价值观; C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆