c/c++结构体几种定义情况总汇

#include <iostream>
#include <malloc.h>
#include <stdio.h>
using namespace std;
struct stu
{
       int *a;
       int *b;
};
int main()
{
    //struct stu *s=new stu[10];
    //struct stu s=new stu;
    stu s = (stu*)malloc(sizeof(stu)+2);
    //struct stu s;
    struct stu s1;//
    for (int i=0; i<4; i++)
    {
        cin>>s.a[i]>>s.b[i];
        cout<<s.a[i]<<" "<<s.b[i]<<endl;
    }
    //delete []s;
    while (1);
    return 0;
}

#define N 10005

struct stu
{
       int a;
       int b;
};

struct stu s[N];


首先,我们搞清几个概念,结构体名,结构体变量,结构体成员

结构体名    正如这样  struct stu s/这里stu 是结构体名,s是结构体变量了,那么里面的a,b都是他的成员了;

//在c++里面,我们发现笔者很喜欢用typedef;例如:

typedef struct stu
{
       int a;
       int b;
}s1,s2;


那么 s1,s2是什么意思呢?   大家都知道 typedef的作用的,顾名思义,我们的s1,s2,就相当 stu   他是结构体名,不是结构体变量,要运用结构体 我们就要定义一个结构体变量;

//像这样
s1 ss;
s2 sss;

接着 问题就来了,结构体成员是否可以和 结构体变量重名呢?  结构体名是否可以和结构体变量名一样呢???

struct stu
{
       int a;
       int b;
};

struct stu a;//struct stu stu;


结构体,在C++中,是一个类而已。所以,不管是类,还是结构体,它产生的对象名,其实是可以与成员同名的。

再试下,

struct stu
{
         int a,b;
}stu;//这时stu已经变成结构体变量了

但是下面的代码又没解释,只能说c很强大啊,下面的代码说明我们还是少重名,以免发生错误

 

#include <iostream>
#include <stdio.h>
using namespace std;
struct stu
{
       int a;
       int b;
};
int main()
{
    struct stu stu[100];
    struct stu s1;//
    for (int i=0; i<4; i++)
    {
        scanf("%d%d",&stu[i].a,&s1.a);
        printf("%d %d ",stu[i].a,s1.a);
    }
    while (1);
    return 0;
}

 下面的是结构体指针的两种定义方式:

1.

#include <iostream>
#include <stdio.h>
using namespace std;
struct stu
{
       int a;
       int b;
};
int main()
{
    struct stu *s=new stu[10];
    struct stu s1;//
    for (int i=0; i<4; i++)
    {
        cin>>s[i].a>>s[i].b;
        cout<<s[i].a<<" "<<s[i].b<<endl;
    }
    delete []s;
    while (1);
    return 0;
}

2.


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值