C语言中main函数中结构体数组传参到别的函数的示例
时间: 2023-02-12 17:43:47 浏览: 81
在 C 语言中, 下面是一个结构体数组传参到别的函数的示例:
```
#include<stdio.h>
struct student
{
int age;
char name[20];
};
void display(struct student s[], int n);
int main()
{
struct student s[3]={{20,"Alice"},{21,"Bob"},{22,"Charlie"}};
display(s, 3);
return 0;
}
void display(struct student s[], int n)
{
int i;
for(i=0; i<n; i++)
{
printf("%d %s\n", s[i].age, s[i].name);
}
}
```
在 main 函数中, 定义了一个结构体数组 s, 并传入到 display 函数中. display 函数通过循环输出结构体数组中每个元素的 age 和 name 属性。
相关问题
c语言的scanf函数在输入结构体数组的时候,是不需要添加取地址符的嘛
在输入结构体数组时,使用scanf函数需要添加取地址符。这是因为scanf函数需要将输入的数据存入到变量的内存地址中,而结构体数组中的每个元素都是一个结构体变量,所以需要将结构体变量的地址作为参数传递给scanf函数,以便将输入的数据存储到结构体数组中。示例代码如下:
```
#include <stdio.h>
struct student {
char name[20];
int age;
};
int main() {
struct student s[3];
int i;
for(i = 0; i < 3; i++) {
printf("请输入第%d个学生的姓名和年龄:", i+1);
scanf("%s %d", s[i].name, &s[i].age);
}
return 0;
}
```
在上面的代码中,我们定义了一个包含3个元素的结构体数组s,然后使用for循环遍历数组,通过scanf函数分别输入每个学生的姓名和年龄。在输入年龄时,需要使用取地址符&将s[i].age的地址传递给scanf函数。
C语言中变长的结构体数组如何初始化
在 C 语言中,如果要定义变长的结构体数组,可以先定义一个指向结构体的指针,然后再动态地为该指针分配内存空间,从而实现变长数组的初始化。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
int age;
};
int main() {
int n = 3;
struct student *s = (struct student*) malloc(n * sizeof(struct student));
if (s == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
for (int i = 0; i < n; i++) {
printf("Enter name and age for student %d: ", i+1);
scanf("%s %d", s[i].name, &s[i].age);
}
printf("The students' information:\n");
for (int i = 0; i < n; i++) {
printf("Name: %s, Age: %d\n", s[i].name, s[i].age);
}
free(s);
return 0;
}
```
在上面的示例代码中,首先定义了一个变量 `n`,表示要创建的结构体数组的长度。然后通过 `malloc()` 函数为指向结构体的指针 `s` 分配内存空间,大小为 `n * sizeof(struct student)`,即结构体的大小乘以数组的长度。接着通过循环为每个结构体成员的 `name` 和 `age` 成员赋值。最后释放已分配的内存空间。
需要注意的是,使用动态内存分配时,需要在程序结束前释放内存,避免内存泄漏。