#include <stdio.h>
#include <stdlib.h>
struct Student //结构体定义一
{
char name[100];
int age;
float score;
};
typedef struct //结构体定义二
{
char *name; //字符指针
int age;
float acore;
}NewStudent;
int main(int argc, const char * argv[]) {
/*
结构体:C语言提供开发者来自定义数据类型
结构体的定义:
struct 结构体名称(最好大写)
{
类型 变量1;
类型 变量2;
...
};
注意:结构体定义,在花括号后面加分号
*/
/*
结构体变量初始化 struct 结构体名 变量名 = {值1,值2,...};
*/
struct Student st = {"Yong",22,98}; //结构体定义一
NewStudent student = {"Yong",22,98}; //结构体定义二
NewStudent student1 = {"Yong",22,98};
//取结构体元素用'.'
printf("%s\n",st.name);
printf("%d\n",st.age);
printf("%.2f\n",st.score);
//求结构体占内存字节数
int length = sizeof(char)*100+sizeof(int)+sizeof(float);
printf("lenfth = %d\n",length);
//用户自己开辟内存 使用malloc函数,在#include<stdlib.h>
char *theName = (char *) malloc(sizeof(char)*100);
char *theName1 = (char *) malloc(sizeof(char)*100);
char *tmp = "张三";
char *tnp = "李四";
theName = tmp;
theName1 = tnp;
student.name = theName;
student1.name = theName1;
printf("%s\n",student.name);
printf("%s\n",student1.name);
return 0;
}
#include <stdlib.h>
struct Student //结构体定义一
{
char name[100];
int age;
float score;
};
typedef struct //结构体定义二
{
char *name; //字符指针
int age;
float acore;
}NewStudent;
int main(int argc, const char * argv[]) {
/*
结构体:C语言提供开发者来自定义数据类型
结构体的定义:
struct 结构体名称(最好大写)
{
类型 变量1;
类型 变量2;
...
};
注意:结构体定义,在花括号后面加分号
*/
/*
结构体变量初始化 struct 结构体名 变量名 = {值1,值2,...};
*/
struct Student st = {"Yong",22,98}; //结构体定义一
NewStudent student = {"Yong",22,98}; //结构体定义二
NewStudent student1 = {"Yong",22,98};
//取结构体元素用'.'
printf("%s\n",st.name);
printf("%d\n",st.age);
printf("%.2f\n",st.score);
//求结构体占内存字节数
int length = sizeof(char)*100+sizeof(int)+sizeof(float);
printf("lenfth = %d\n",length);
//用户自己开辟内存 使用malloc函数,在#include<stdlib.h>
char *theName = (char *) malloc(sizeof(char)*100);
char *theName1 = (char *) malloc(sizeof(char)*100);
char *tmp = "张三";
char *tnp = "李四";
theName = tmp;
theName1 = tnp;
student.name = theName;
student1.name = theName1;
printf("%s\n",student.name);
printf("%s\n",student1.name);
return 0;
}