A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wwf707542865 中级黑马   /  2015-10-2 16:37  /  818 人查看  /  10 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

#include <stdio.h>

struct person{
    char    *name;
    int     age;
    float   high;
};
int main()
{
   
    struct person{
        char    *name;
        int     age;
    };
    struct person f={"father",51};
    printf("father=%s,age=%d\n",f.name,f.age);
    struct person m={"mother",50,160.0f};
    printf("mather=%s,age=%d,high=%.1f\n",m.name,m.age,m.high);
   
    return 0;
}
我定义的struct person m报错了,我初始化多了一个float,难道不能自动往上找,匹配到那个全局结构体么,很疑惑,求解答,谢谢!

10 个回复

倒序浏览
这个肯定不对啊,你main函数里面有定义了一个struct函数,会屏蔽外面的函数, struct person m={"mother",50,160.0f};多了个变量hight去掉160.0f就可以了
回复 使用道具 举报
不会,内部变量会屏蔽外部变量,在main内只会找main内定义的person
回复 使用道具 举报
局部变量屏蔽全局变量
回复 使用道具 举报

#include <stdio.h>

/*************************************************
   
全局变量
struct person{
            char    *name;
            int     age;
            float   high;
            };


**************************************************/

int main()
{
   
    struct person1{
        char    *name;
        int     age;
    };
    struct person2{
        char    *name;
        int     age;
        float   high;
    };
    /*****************************
     结构体全局变量和普通变量一样
     遵循就近原则
     ****************************/
    struct person1 f={"father",51};
    printf("father=%s,age=%d\n",f.name,f.age);
    struct person2 m={"mother",50,160.0f};
    printf("mather=%s,age=%d,high=%.1f\n",m.name,m.age,m.high);
    return 0;
}
回复 使用道具 举报
HI奋斗 发表于 2015-10-2 16:43
这个肯定不对啊,你main函数里面有定义了一个struct函数,会屏蔽外面的函数, struct person m={"mother",5 ...

哦,这样啊,我还以为可以根据参数来自动匹配呢,谢谢
回复 使用道具 举报
8430110 发表于 2015-10-2 16:59
#include

/*************************************************

谢谢,明白了
回复 使用道具 举报
杰杰 中级黑马 2015-10-2 20:14:55
8#
肯定错,局部结构体把全局结构体屏蔽了。
回复 使用道具 举报
chensc 金牌黑马 2015-10-3 07:47:00
9#
学习学习!
回复 使用道具 举报
内部的person结构体会自动屏蔽全局person结构体类型,从而在main函数内给person类型变量m多赋值一个高度的值是会报错的。。
回复 使用道具 举报
就近原则
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马