优秀的编程知识分享平台

网站首页 > 技术文章 正文

C语言结构体定义与赋值

nanyue 2025-03-12 18:54:42 技术文章 54 ℃

在了解结构体是一种复杂的数据类型之后,我们来看看结构体是如何定义的。定义结构体有三种方法

方法一,创建结构体,声明结构体变量

struct Student{
    int age;
    char sex;
};

声明结构体变量

struct Student st = {30,’男’};

方法二,在定义结构体时,直接定义变量名

struct Student{
    int age;
    char sex;
} st;

方法三,直接定义结构体变量名

struct{
    int age;
    char sex;
} st;

此方法定义不清晰,不知道结构体名称是声明。

其中最常用的是方式一,先定义结构体,再使用结构体声明变量。在使用结构体时,建议使用方式一。

结构体赋值与初始化

定义结构体Student。

struct Student{

int age;

char sex;

};

(1)声明结构体变量st,同时进行赋值。

struct Student st = {30,’男’};

(2)声明结构体变量st2,再通过形如st2.age这样的形式进行赋值

struct Student st2;

st2.age = 30;

st2.sex = ‘女’;

程序演示,使用方式一定义结构体,并进行赋值

#include
struct Student{
    int age;
    char sex;
};
int main(void){
    struct Student st;
    st.age = 30;
    st.sex = 'm';
    printf("年龄:%d,性别:%c",st.age,st.sex);
    return 0;
} 


以上示例定义了结构体Student,声明结构体变量st,使用结构体变量名.成员的形式进行赋值并输出。

最近发表
标签列表