作业:C 编程 - 结构体和数组
我的作业需要使用以下链表结构:
struct studentNode { int id; char *fname; char *lname; int programs[x]; int labs[x]; int exams[x]; int percent; double grade; struct studentNode *next; };
我的问题是,程序、实验和考试的数组正在从文件中加载,并且长度可变。
我尝试使用指向数组的指针,但是每当我为新学生更新数组时,它都会替换链接列表中每个人的分数。
我试着和教练讨论这个问题,他让我用谷歌搜索一下。 :(
到目前为止,我还没有任何运气,这超出了我们本书涵盖的范围。
任何帮助将不胜感激。
My assignment requires the use of the following linked list structure:
struct studentNode { int id; char *fname; char *lname; int programs[x]; int labs[x]; int exams[x]; int percent; double grade; struct studentNode *next; };
My problem is, the arrays for programs, labs and exams are being loaded from a file and are to be variable lengths.
I tried using a pointer to the array, however whenever I updated the array for a new student it would replace the scores for everyone in the linked list.
I've tried going over this with the instructor and he tells me to google it. :(
So far, I haven't had any luck and it's beyond the scope of what our book covers.
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据您的描述:
您需要为数组中的每个项目创建一个新对象。
因此,首先您创建一些东西来保存第一项(例如指向第一项的指针)。然后,当您加载每个项目时,创建新的 StudentNode 并将其添加到数组中。
From what you describe:
You need to create a new object for each item in the array.
so first you create something to hold the first item (like a pointer to the first item). Then as you load each item, create new studentNode and then add it to the array.
确保每个
studentNode
不共享相同的programs
、labs
等数组。除了创建studentNode
之外,您还必须在其中创建数组。Make sure each
studentNode
isn't sharing the sameprograms
,labs
, etc arrays. In addition to creating thestudentNode
, you have to create the arrays within them.我相信您的问题是指如何指定程序、实验室和考试数组的大小。
不要将数组存储在结构中,而是保留指向数组的指针。然后,在结构外部构建程序数组后(如有必要,使用 malloc)将 node.program 指针重新分配给该数组。
I believe your question is referring to how to specify the size of the programs, labs, and exams arrays.
Instead of storing the array in your struc, keep a pointer to your array. Then, after you have built your program array outside of your structure (using malloc if necessary) reassign your node.program pointer to that array.
听起来您对所有学生使用相同的数组。您需要为每个学生分配一个单独的数组。
您可以在二维数组中静态分配固定数量的元素:
在这种情况下,您需要将每个 StudentNodes 数组指向正确的数组(对于每个学生)。
或者在堆上为每个学生分配一些内存。
It sounds like you are using the same array for all students. You need to allocate a separate array for each student.
You can either statically allocate a fixed number of elements in a 2d array:
In this case you will need to point each studentNodes array to the correct array(for each student).
Or allocate some memory on the heap for each student.