在用户需要时创建一个新的struct变量

时间:2016-01-11 17:06:01

标签: c struct

我刚刚开始使用C,并遇到struct的问题。比如我有:

struct student {
    int id;
    char name[25]
};

我希望用户根据需要添加尽可能多的学生:

int count = 0;
while (stop == 0){
    struct student count
    scanf("%d", count.id); 
    scanf("%s", count.name);
    scanf("%d", stop);
}

看起来我创建struct student count(其中count是一个数字)并继续创建它们。所以,我想创建类似struct student 0,然后struct student 1等等的内容,以便我可以通过它的计数或数字来引用每个学生。 我怎么能得到这样的东西呢?

2 个答案:

答案 0 :(得分:2)

这将在用户请求时自动分配内存。它从1的维度开始,直到几乎无限(实际上,直到RAM中可用的空间)。 当然,如果需要,您可以更改size的初始大小以及数组的增长率。

// Example program
#include <stdio.h>      /* printf, scanf */
#include <stdlib.h>         /* for realloc, malloc */

// Supposing student is defined like this: 
struct student 
{ 
  int id; 
  char name[25];
};

int main()
{
  int stop = 0;
  int count = 0;
    int size = 0;

    // Using an array of students
    size = 1;
  struct student* students = malloc(size * sizeof(struct student));

  while (stop == 0)
  {
        if(count >= size)
        {
            size ++;
            students = realloc (students, size * sizeof(struct student));

            if (students == NULL)
            {
                printf ("Failed to allocate more memory.\n");
                return 0;
            }
        }   

    scanf("%d", &(students[count].id)); 
    scanf(" %24[0-9a-zA-Z ]", &(students[count].name));
    scanf("%d", &stop);
    count = count + 1;
  }

  int i = 0;
  for (i = 0; i < count; ++i)
    printf("%d => %d  %s\n", i, students[i].id, students[i].name);
}

答案 1 :(得分:1)

我认为您希望在控制台中输入的每个用户的第一个代码示例中为结构创建多个实例,由{{1 }} - 环

实现这一目标的最简单方法是使用数组。我建议你先使用一个固定大小的数组,这意味着你在代码中指定数组大小。此数组允许您将学生实例添加到您指定的数组大小中。

一个简单的例子是这样的:

while

在上面的示例中,我添加了一个固定大小为128的数组,您可以将其更改为您喜欢的任何大小。在// Define the student struct struct student { int id; char name[25]; }; // ... // Create an array with a fixed size to put the students in, and define a counter struct student students[128]; int count = 0; while(stop == 0){ // Create the struct to fill struct student newStudent; // Fill the struct with the user supplied data scanf("%d", newStudent.id); scanf("%s", newStudent.name); scanf("%d", stop); // Add the struct to the array, and increase the count afterwards students[count++] = newStudent; } - 循环中,创建了一个新结构的实例,这与之前类似。之后使用从控制台提供的数据填充此结构。在while循环结束时,struct实例被添加到学生数组中。这将为您提供一系列您已输入的学生。

然而,这个解决方案存在一个缺点,并且在大多数情况下,消耗的内存比实际使用的内存多得多。这是因为对于计算机来说,感觉就像128个整个实例(或任何其他数组大小,如果指定的话)存储在RAM中,如果真的只使用两个实例,这可能会非常昂贵。另外,正如我之前所说,请务必记住,修复数组大小会限制条目数量,这也会对代码产生负面影响。如果您不想产生这些后果,您可能需要查看下面描述的解决方案。

您可以使数组的大小动态,这是更先进的。如果您想要达到这样的效果,请务必查看memory allocation functions,例如评论中指出的Sourav Ghosh。您可能还想查看the code-example Michael制作的内容。

我希望这有助于解决您遇到的问题。快乐的编码!