首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在C中正确地为结构数组分配内存?

如何在C中正确地为结构数组分配内存?
EN

Stack Overflow用户
提问于 2015-03-09 03:40:16
回答 1查看 12.9K关注 0票数 4

这是我第一次使用structs,因为我对C语言还是比较陌生的。当我尝试为3个structs输入值时,程序崩溃了,但它对1和2都很好。我想我实际上可能没有分配足够的内存。这是为结构数组分配内存的正确方式吗?

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

#define MIN_SIZE 0
#define MAX_SIZE 100
#define MAX_MONTH_STR 9

//Define a struct data type
typedef struct
{
    char* month;
    int day;
    int year;
}date;

//Method to allocate memory for a list of date structures
date* allocateStruct(int size)
{
    //Declaration of variables
    date *array;
    int i;

    //Allocate memory for rows (to store 'size' many pointers to 'date' struct data type)
    array = malloc(size*sizeof(date*));

    //For-loop to allocate memory for columns (to store 'size' many integers, and initialize them to zero)
    for (i=0; i<size; i++)
    {
        array[i].month = calloc(MAX_MONTH_STR,sizeof(char));
        array[i].day = calloc(1,sizeof(int));
        array[i].year = calloc(1,sizeof(int));
    }

    return array;
}

//Method to free memory allocated
//TO DO. . .

int main()
{
    //Declaration of variables
    int n;
    date* date_list;
    int i, j, k; //used in loops

    //Read input
    do
    {
        //printf("Enter number of dates you want to enter (between 1 and 10000):\n");
        scanf("%d", &n);
    }while(n<MIN_SIZE || n>MAX_SIZE);

    //ALLOCATE MEMORY
    date_list = allocateStruct(n);


    //For-loop to store values in 'date_list'
    for (i=0; i<n; i++)
    {
        //printf("Enter the date (month day year) in the following format: text number number");
        scanf("%s", date_list[i].month);
        scanf("%d", &date_list[i].day);
        scanf("%d", &date_list[i].year); //need & ?
    }

//--------> crashes here if 3 dates are input, ok for 1 and 2

    //Test print
    for (i=0; i<n; i++)
    {
        //printf("Enter the date (month day year) in the following format: text number number");
        printf("%s ", date_list[i].month);
        printf("%d ", date_list[i].day);
        printf("%d\n", date_list[i].year); //need & ?
    }

    return 0;
}
EN

Stack Overflow用户

回答已采纳

发布于 2015-03-09 03:43:35

您正在尝试使用指向日期结构的指针大小而不是日期结构的实际大小来分配数组。

date*更改为date

array = malloc(size*sizeof(date));

此外,您不需要分配日期和年份变量,因为malloc会为您分配它们。

代码语言:javascript
复制
for (i=0; i<size; i++)
{
     array[i].month = calloc(MAX_MONTH_STR,sizeof(char));
     array[i].day = 0;
     array[i].year = 0;
}
票数 5
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28931034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档