简体   繁体   English

C语言中的动态结构数组

[英]dynamic array of structs in C

I am trying to learn about structs, pointers, and dynamic arrays in C. I don't understand how to create a dynamic array of structs using pointers. 我试图在C中学习结构,指针和动态数组。我不明白如何使用指针创建动态结构数组。 My code doesn't work, and I don't know what's wrong with it. 我的代码不起作用,我不知道它有什么问题。 I have seen several examples of dynamic arrays, but non with structs. 我见过几个动态数组的例子,但是没有结构。 Any help would be appreciated. 任何帮助,将不胜感激。 Please give some explanation, not just code snippets as I do want to understand not just solve this problem. 请给出一些解释,而不仅仅是代码片段,因为我想要理解的不仅仅是解决这个问题。

#include<stdio.h>
#include<stdlib.h>
#include <string.h>

struct *struct_array;
int i,m,n,p;

struct data
{
    char inputA[20];
    char inputB[20];    
};

struct data get_data()
{
    struct data thisdata;

    printf("Please enter input A\n");
    scanf("%s", thisdata.inputA);

    printf("Please enter input B\n");
    scanf("%s", thisdata.inputB);

    return thisdata;
}

void Output(struct data struct_array, int n)
{
    int index = 0;
    for(i = 0; i<n ;i++)
    {
        printf("%s ", struct_array[i].inputA);
        printf("%s ", struct_array[i].inputB);
    }   
}

void resizeArray(int n)
{
    struct_array = (int*)realloc(n*sizeof(int));
}

void mainMenu()
{
    printf("Please select from the following options:\n");
    printf("1: Add new students to database\n");
    printf("2: Display current student database contents\n");
    printf("3: exit the program\n");
    scanf("%d", &p);
    if(p == 1)
    {
        printf("Please enter the number of students to register:\n");
        scanf("%d", &n);
        resizeArray(n);
        for(i = n; i<n ;i++)
        {
            struct_array[i] = get_data();
        }
    }
    else if(p == 2)
    {
         Output(struct_array, n);
    }
    else
    {
        free(struct_array);
        exit(0);
    }        
}

int main()
{    
    struct_array = (int*)realloc(2*sizeof(int));
    mainMenu();
}

You have several errors in your source code: 您的源代码中有几个错误:

  • struct *struct_array; (l. 5) (l.5)
    What does it mean? 这是什么意思? Did you want to write struct data *struct_array ? 你想写struct data *struct_array吗?

  • printf("%s ", struct_array[i].inputA); (l.32 & l. 33) (l.32&l.33)
    The argument struct_array masks the global declaration, and it is not an array. 参数struct_array掩盖了全局声明,它不是数组。 Why did you add this argument? 你为什么要加上这个论点?

  • struct_array = (int *)realloc(n * sizeof(int)); (l. 39) (l.39)
    You have forgotten an argument. 你忘记了一个论点。 Did you want to use malloc instead? 你想使用malloc吗? Besides, the cast is not necessary (and incorrect!). 此外,演员不是必要的(并且不正确!)。

  • Unless you are using an hosted environnment and C99/C11, you should return a value from main . 除非您使用托管环境和C99 / C11,否则您应该从main返回一个值。

  • Your variable index is not used. 您的变量index未使用。 Why did you declare it? 你为什么要申报呢?

  • for(i = n; i < n; i++) (l. 53) You won't have any iteration here... for(i = n; i < n; i++) (l.53)你在这里不会有任何迭代......

The following code works as expected. 以下代码按预期工作。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* TODO: Avoid global variables. */
struct data *struct_array;

struct data {
    char inputA[20];
    char inputB[20];
};

/* 
 * TODO: Try to avoid passing your structure (40 bytes + padding) 
 * without pointer. 
 */
struct data get_data(void)
{
    struct data thisdata;

    printf("Please enter input A\n");

    /* TODO: Avoid using `scanf` for human inputs. */
    scanf("%s", thisdata.inputA);

    printf("Please enter input B\n");
    scanf("%s", thisdata.inputB);

    return thisdata;
}

void Output(size_t n)
{
    size_t i;
    for (i = 0; i < n; i++) {
        printf("%s ", struct_array[i].inputA);
        printf("%s ", struct_array[i].inputB);
    }
}

void resizeArray(size_t n)
{
    /* TODO: Handle reallocations errors. */
    struct_array = realloc(struct_array, n * sizeof *struct_array);
}

void mainMenu(void)
{
    size_t i, n;
    int p;

    /* TODO: Use a loop ? */
    printf("Please select from the following options:\n");
    printf("1: Add new students to database\n");
    printf("2: Display current student database contents\n");
    printf("3: exit the program\n");
    scanf("%d", &p);

    switch (p) {
    case 1:
        printf("Please enter the number of students to register:\n");
        scanf("%u", &n);
        resizeArray(n);

        for (i = 0; i < n; i++)
            struct_array[i] = get_data();
        break;
    case 2:
        Output(n);
        break;
    }
}

int main(void)
{
    struct_array = malloc(2 * sizeof(int));
    mainMenu();
    free(struct_array);
    return 0;
}

Your definition 你的定义

struct *struct_array;

is erroneous. 是错误的。 You must use the name of your type, the data . 您必须使用您的类型名称和data

struct data *struct_array;

This way you can allocate the array 这样就可以分配数组了

struct_array = malloc(MaxNumElements * sizeof(struct data));

and later you should free the memory 然后你应该释放记忆

free(struct_array);

EDIT: Type definition must occur before the var declaration. 编辑:类型定义必须在var声明之前发生。

struct data ....

struct data* your_variable;

PS If you do not want to type struct keyword each time you use the data type, use the typedef : PS如果您不想在每次使用data类型时键入struct关键字,请使用typedef

typedef struct data_s
{
   char inputA[20];
   char inputB[20];    
} data;

Do you know how to use typedef? 你知道如何使用typedef吗?

I would suggest it, makes your code easier to understand and you won't have to be typing the word struct a thousand times. 我建议它,使你的代码更容易理解,你不必键入struct一千次。 Also you could treat the new type similar to the primitive types (ints, chars, etc), just don't forget to use the dot (.) to access the individual fields you might want. 您也可以将新类型视为与原始类型(整数,字符等)类似,只是不要忘记使用点(。)来访问您可能想要的各个字段。

You could type for instance: 你可以输入例如:

    typedef struct{
      char inputA[20];
      char inputB[20];
    } data;

Now you could declare variables like this: 现在您可以声明这样的变量:

   data data_variable;
   data *pointer_to_data;

And to you could allocate memory as follows: 你可以按如下方式分配内存:

   pointer_to_data = (data*) malloc(sizeof(data)* N);

where N is the amount of struct data you want to allocate. 其中N是您要分配的struct数据量。 Same works for realloc. 同样适用于realloc。

struct_array = (int*)realloc(2*sizeof(int)); struct_array =(int *)realloc(2 * sizeof(int));

By the above statement you are trying to assign address of an int to a pointer of type struct data . 通过上面的语句,您尝试将int的地址分配给struct data类型的指针。

You need to use: 你需要使用:

struct_array = (struct data*)realloc(2*sizeof(struct data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM