c - 使用循环在 C 中创建新结构
问题描述
在这里,我创建了一个以姓名、卷号、分数等为成员的学生结构。所以,我想做的是每次迭代循环时创建一个新结构,并在循环时将数据保存在其中。
所以,我创建了一个变量stdname
,每次迭代都会改变它的值,并用它来命名一个新学生,但它不起作用。我对C相当陌生,我不知道我的代码有什么问题。
#include <stdio.h>
struct Marks
{
int phy;
int chem;
int math;
};
struct Student{
char name[50];
int rollN0;
char remarks[100];
struct Marks marks;
};
int main()
{
for (int i=0; i<10; i++)
{
char stdname[50];
sprintf(stdname,"student%d",i+1);
struct Student stdname;
printf("Enter the following data of Student No. %d:\n", i+1);
//taking data from user and storing
}
}
解决方案
我建议您通过实施链表或标签系统来解决您的问题。我个人更喜欢链表,因为当你的代码进化时,在我的 pov 中使用链表会更容易。
所以在代码中你会在你的结构中看到我添加了一个next
指针,这个指针将存储另一个学生的地址,如果下一个是NULL
那么我们可以确认没有更多的学生,我们可以停止在列表中爬行。
函数添加使用此原理;她走到列表的末尾,然后将 替换为next
新学生结构的地址。而且因为新结构的下一个是NULL
这个过程,它可以重复使用
该功能create_new_node
只是数据初始化和内存分配。它看起来很丑,因为我真的不知道你想要存储什么。
❗我没有测试这段代码,它根本没有优化❗</p>
#include <stdio.h>
#include <stdlib.h> // for malloc function
struct Marks
{
int phy;
int chem;
int math;
};
struct Student{
char name[50];
int rollN0;
char remarks[100];
struct Marks marks;
struct Student* next; // I had this
};
/// new ///
void add_node_to_list(struct Student* node, struct Student* list)
{
while (list->next != NULL)
list = list->next;
list->next = node;
}
struct Student* create_new_node(struct Student data)
{
struct Student* new_node = malloc(sizeof(struct Marks));
if (!new_node)
return NULL;
new_node->name = data.name;
new_node->rollN0 = data.rollN0;
new_node->remarks = data.remarks;
new_node->marks = data.marks;
new_node->next = NULL;
return new_node;
}
/// end-new ///
int main(void /* new */)
{
struct Student* list = NULL;
struct Student* new_node = NULL;
for (int i=0; i<10; i++)
{
char stdname[50];
sprintf(stdname,"student%d",i+1);
/// new ///
if (!list) { // first the first element
list = create_new_node((struct Marks) {stdname, 0, "\0", {0, 0, 0}, NULL});
if (!list) // check for malloc errors
return 1;
} else { // every time there is a new student
new_node = create_new_node((struct Marks) {stdname, 0, "\0", {0, 0, 0}, NULL});
if (!new_node) // check for malloc errors
return 1;
add_node_to_list(new_node, list);
}
/// end-new ///
printf("Enter the following data of Student No. %d:\n", i+1);
//taking data from user and storing
}
return 0; // new: your main should always return a value. Compile with W flags see: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
}
这是我的建议,如果我笨拙,请注意我,我是堆栈上的新用户。
也随时提出问题或修复我自己的错误
希望我帮助了你
推荐阅读
- reactjs - React - Redux 错误:连接后元素类型无效
- arrays - presto 从 varchar 列表中过滤项目
- sql - SQL 问题使用内连接重复列名和缺少右括号
- swift - 如何使用 CVPixelBuffer/IOSurface 更新 CALayer?
- php - PHP群发邮件程序的最佳方法?
- java - Spring Boot Modelmapper - StackOverflowError:null
- json - Cors 策略阻止 JSON 请求
- visual-studio - 不使用预编译头文件,但得到“PDB 与构建此预编译头文件时不同”错误”
- ios - 在 Xcode 中找不到模块“flutter_local_notifications”
- python - Plotly range_slider 限制