如何让结构体数组存储字符串后完整的读取出来,给出示例
时间: 2024-02-03 07:14:09 浏览: 12
可以使用字符串指针来存储字符串。下面是一个示例代码,可以将字符串存储到结构体数组中,并完整读取出来:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 50
#define MAX_NUM_STUDENTS 100
typedef struct {
char *name;
int age;
} Student;
int main() {
Student students[MAX_NUM_STUDENTS];
int num_students;
char buffer[MAX_NAME_LENGTH];
printf("Enter the number of students: ");
scanf("%d", &num_students);
for (int i = 0; i < num_students; i++) {
printf("Enter the name of student %d: ", i+1);
scanf("%s", buffer);
students[i].name = malloc(strlen(buffer)+1);
strcpy(students[i].name, buffer);
printf("Enter the age of student %d: ", i+1);
scanf("%d", &students[i].age);
}
printf("\nStudent details:\n");
for (int i = 0; i < num_students; i++) {
printf("Name: %s, Age: %d\n", students[i].name, students[i].age);
free(students[i].name);
}
return 0;
}
```
在上面的示例代码中,我们使用了 `char *name` 来存储学生的名字。当我们读取学生的名字时,我们将其存储到 `buffer` 中,并将 `buffer` 中的内容复制到 `students[i].name` 中。这样可以确保 `students[i].name` 指向的内存中存储的内容是完整的字符串。
在输出学生信息时,我们使用了 `%s` 格式化字符串来输出学生的名字。最后,我们需要释放每个学生的名字所占用的内存。
注意,这里我们使用了 `malloc` 函数来为 `name` 分配内存。这样做是为了确保 `name` 指向的内存是动态分配的,并且可以在需要时释放。