测试源码
#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;
}