如何对结构体成员赋值和初始化

// 结构体的赋值和初始化.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>

//定义结构体
struct Student
{
	float score;
	char sex;
	char name[20];
};

int main(void)
{
	int i = 0;//在c语言中,所有的定义必须放在执行语句之前
	struct Student st1 = {100, 'm', "Xiexiaodong"};//第一种,定义的同时初始化,类似数组,定义后在整体赋值会出错
	struct Student st2;
	//st2 = {100, 'm', "Xiexiaodong"};//error, 应该单独赋值
	st2.score = 100;
	st2.sex = 'm';
	gets(st2.name);//输入名字,要不一个一个的对数组赋值
	printf("%f,%c,%s\n", st1.score, st1.sex, st1.name);
	printf("%f,%c,", st2.score, st2.sex);
	puts(st2.name);
	printf("\n");

	return 0;
}


补充:对字符数组赋值还可以用strcpy函数实现:

#include "stdafx.h"
#include <stdio.h>
#include <string.h>

struct Student 
{
	char name[100];
};

int main(void)
{
	struct Student st;

	strcpy(st.name, "解晓东");

	puts(st.name);

	return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值