c语言_Day9_07_08

1、初识结构体

对于相对复杂的数据,如人、书、车辆等,可通过结构体对其进行定义

struct关键字可定义结构体类型,也可创建结构体变量,通过“.”操作符可访问结构体变量内的字段

int main()
{
	struct Book	// 定义结构体类型
	{
		char name[20];
		float price;
	};

	struct Book book = { "Math", 20.59 };	// 创建结构体变量
	printf("Book name: %s\n", book.name);
	printf("Book price: %f\n", book.price);

	return 0;
}

对于结构体变量的指针,与普通指针变量特点一致,但可通过“->”操作符直接访问指针指向的变量的成员

int main()
{
	struct Student
	{
		char name[10];
		int age;
		int score;
	};

	struct Student stu = { "Tom", 18, 90 };
	struct Student* p = &stu;
	printf("Name: %s  age: %d  score: %d\n", stu.name, stu.age, stu.score);
	printf("%p\n", p);
	printf("Name: %s  age: %d  score: %d\n", (*p).name, (*p).age, (*p).score);
	printf("Name: %s  age: %d  score: %d\n", p->name, p->age, p->score);

	return 0;
}

注:由于字符串的本质为字符数组,故无法直接修改其值,可通过strcpy函数遍历数组进行修改

for (int i = 0; i < strlen(p.name); i++)
	{
		p.name[i] = 65 + i;
	}
	printf("%s\n", p.name);
strcpy(p.name, "Bill");
printf("%s\n", p.name);