2015-03-08 41 views
1

這是我第一次使用結構體,因爲我對C還是比較新的。當我嘗試輸入3個結構體的值時,程序崩潰了,但對於1和2它可以正常工作。我想我可能實際上並不是分配足夠的內存。這是爲結構數組分配內存的正確方法嗎?如何正確地爲C中的結構數組分配內存?

#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; 
} 

回答

2

您試圖分配一個指向date結構的指針大小的數組,而不是date結構的實際大小。

變化date*date

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

而且你不需要分配日和年的變量,因爲的malloc分配它們。

for (i=0; i<size; i++) 
{ 
    array[i].month = calloc(MAX_MONTH_STR,sizeof(char)); 
    array[i].day = 0; 
    array[i].year = 0; 
} 
+0

ohh yes你是對的,謝謝! – Yiannis 2015-03-08 19:47:02