结构体内变量赋值暂且分为三种(笔者此时只能想到三种)
1.定义时赋值
2.定义后对变量挨个赋值
3.利用函数进行赋值
赋值时再分为两类
1.非数组赋值
2.数组赋值
1.比较简单,在此不做过多介绍,只是简单贴下代码。
-
struct student{
-
char name[];
-
int age;
-
}b;
-
-
int main(){
-
struct student a = {
"LiMing",
10};
-
}
定义后对变量挨个赋值-非数组赋值
-
struct student{
-
int age;
-
double hight;
-
}b;
-
-
int main(){
-
b.age =
12;
-
b.hight =
184.0;
-
printf(
"%d %f\n",b.age,b.hight);
-
system(
"pause");
-
}
直接赋值即可。
2.2
定义后对变量挨个赋值-数组赋值
C语言中规定数组初始化时可以赋值,但初始化之后再赋值是不合法的.
比如
char a[10] = "asdad";
这是合理的。
-
char a[
10];
-
a[
10] =
"1234";
这是不合理的
例:
int i[10]; i[1] = 1;
但此种方法过于繁琐 因此笔者看过很多大神用地址的方法进行赋值
方法如下(此方法只适用于字符数组,其他数组请用单个元素赋值方法)
-
struct student{
-
char *name;
-
int age;
-
double hight;
-
}b;
-
-
int main(){
-
b.name =
"LiMing";
-
b.age =
12;
-
b.hight =
184.0;
-
printf(
"%s %d %f\n",b.name,b.age,b.hight);
-
system(
"pause");
-
}
3.利用函数进行赋值
(需引入string.h头文件,此时字符数组不必是地址)
内部函数的调用
-
#include
-
struct student{
-
char name[
10];
-
int age;
-
double hight;
-
}b;
-
-
int main(){
-
strcpy(b.name,
"LiMing");
-
b.age =
12;
-
b.hight =
184.0;
-
printf(
"%s %d %f\n",b.name,b.age,b.hight);
-
system(
"pause");
-
}
-
struct student{
-
char *name;
-
int age;
-
double hight;
-
}b;
-
void f(
struct student *p){
-
p->name =
"LiMing";
-
p->age =
12;
-
p->hight =
184.0;
-
}
-
int main(){
-
f(&b);
-
printf(
"%s %d %f\n",b.name,b.age,b.hight);
-
system(
"pause");
-
}