当前位置:   article > 正文

结构体的赋值和初始化(以及字符串数组如何赋值)_结构体中字符数组初始化

结构体中字符数组初始化
#include <stdio.h>
#include <string.h>
//定义结构体的第1种方式,推荐使用该方式 
struct Student{
	int age;
	char name[50];
	float height;
};//相当于定义了一个数据类型 


int main(void) {
	struct Student student1 = {20,"xurong",174.5};//定义一个变量时,并直接对其赋值 
    struct Student student2;
    student2.age = 21;
    strcpy(student2.name, "Tome");//不能直接赋值,需调用strcpy函数
//char *strcpy( char *dest, const char *src );
//1) 复制 src 所指向的空终止字节字符串,包含空终止符,到首元素为 dest 所指的字符数组。
//若 dest 数组长度不足则行为未定义。若字符串覆盖则行为未定义。若 dest 不是指向字符数组的指针或 
//src 不是指向空终止字节字符串的指针则行为未定义。
    student2.height = 180.0;
    printf("%d %s %lf\n",student1.age,student1.name,student1.height);
    printf("%d %s %lf\n",student2.age,student2.name,student2.height);
	return 0;
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

输出:

20 xurong 174.500000
21 Tome 180.000000
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/730748
推荐阅读
相关标签
  

闽ICP备14008679号