结构体数组的使用

测试源码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

typedef struct stu{
	
	char name[32];
	int age;
	int score;
}stu;

int main(int argc, const char *argv[])
{
	printf("main addr is %p\n",main);
	stu stu[5];
	stu[0].age = 18;
	stu[0].score = 90;
	strcpy(stu[0].name,"zhangsan");
	
	(stu+1)->age = 19;
	(stu+1)->score = 99;
	strcpy((stu+1)->name,"lisi");
	
	(*(stu+2)).age = 20;
	(*(stu+2)).score = 77;
	strcpy((*(stu+2)).name,"wangwu");
	
	printf("stu[0].age = %d\n",stu[0].age);
	printf("stu[0].score = %d\n",stu[0].score);
	printf("stu[0].name = %s\n",stu[0].name);
	
	puts("*****************************************************");
	
	
	
	printf("(stu+1)->age = %d\n",(stu+1)->age);
	printf("(stu+1)->score = %d\n",(stu+1)->score);
	printf("(stu+1)->name = %s\n",(stu+1)->name);
	
	puts("*****************************************************");
	
	
	
	printf("(*(stu+2)).age = %d\n",(*(stu+2)).age);
	printf("(*(stu+2)).score = %d\n",(*(stu+2)).score);
	printf("(*(stu+2)).name = %s\n",(*(stu+2)).name);
	
	puts("*****************************************************");
	
	
	
	
	return 0;
}

测试结果

在这里插入图片描述

关键代码分析

表示结构体成员的三种方式

1、.方式
stu[0].age = 18;
stu[0].score = 90;
strcpy(stu[0].name,"zhangsan");
2、->方式
(stu+1)->age = 19;
(stu+1)->score = 99;
strcpy((stu+1)->name,"lisi");
3、先*成员再.方式
(*(stu+2)).age = 20;
(*(stu+2)).score = 77;
strcpy((*(stu+2)).name,"wangwu");
(*(stu+2)).age分析

(stu+2)为一个地址,(stu+2)得到数组成员,((stu+2)).age,得到数组成员里具体的内容的方式。
因为.的优先级高,所以前面需要加括号。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Teacher
{
	char name[50];
	//char *name;
	int age;
}Teacher;

int main(void)
{
	Teacher a[3] = {
		{ "a", 18 },
		{ "a", 18 },
		{ "a", 18 }
	};

	//静态
	Teacher a2[3] = { "a", 18, "b", 28, "c", 38 };
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		printf("%s, %d\n", a2[i].name, a2[i].age);
	}

	//int a[3]
	//int *, sprintf()

	int b[3] = { 0 };
	int *pB = (int *)malloc(3 * sizeof(int));
	free(pB);

	//Teacher p[3]
	Teacher *p = (Teacher *)malloc(3 * sizeof(Teacher));
	if (p == NULL)
	{
		return -1;
	}

	char buf[50];
	for (i = 0; i < 3; i++)
	{
		sprintf(buf, "name%d%d%d", i, i, i);
		strcpy(p[i].name, buf);
		p[i].age = 20 + i;
	}

	for (i = 0; i < 3; i++)
	{
		printf("%d:%s:%d\n", i+1, p[i].name, p[i].age);
	}
	printf("\n");

	if (p != NULL)
	{
		free(p);
		p = NULL;
	}

	return 0;
}

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值