我在运行程序时遇到问题,CodeBlocks中没有出现警告或错误。当我创建指针类型的ArrayList结构并尝试使用malloc动态分配内存时,就会遇到麻烦。我正在使用语法' - >。'我已经在这几个小时没有真正的线索了。
#include <stdio.h>
#include <string.h>
#define DEFAULT_INIT_LEN 10//this is in another header file
typedef struct ArrayList{//this is also in another header file
char **array;
int size;
int capacity;
} ArrayList;
int main(void){
ArrayList *test=createArrayList(12);
printf("size: %d capacity: %d\n", test->size, test->capacity);
}
ArrayList *createArrayList(int length){
int i=0;//index variables
ArrayList *r;
if (length>DEFAULT_INIT_LEN){
r->array=malloc(sizeof(char)*(length+1));//create memory for internal array
r->capacity=length;
r->size=0;
for (i=0; i<length; i++)//sets members in the array to NULL
r->array[i]=NULL;
printf("Created new ArrayList of size %d\n", length);
}
else{
r->array=malloc(sizeof(char)*(DEFAULT_INIT_LEN+1));//create memory for internal array
r->capacity=DEFAULT_INIT_LEN;
r->size=0;
for (i=0; i<DEFAULT_INIT_LEN; i++)//sets members in the array to NULL
r->array[i]=NULL;
printf("Created new ArrayList of size %d", DEFAULT_INIT_LEN);
}
return r;
}
答案 0 :(得分:2)
ArrayList *
createArrayList(int length)
{
ArrayList *r = malloc(sizeof(*r));
if (r == NULL) return NULL;
length = MAX(length, DEFAULT_INIT_LEN); // do not duplicate code. ever.
r->array = calloc(length + 1, sizeof(r->array[0]));
if (r->array == NULL) { free(r); return NULL; } // always check pointers
r->size = 0;
r->capacity = length;
printf("Created new ArrayList of size %d\n", length);
return r;
}
您可能不想分配length + 1
元素,因为您有r->capacity
。
答案 1 :(得分:1)
你必须先初始化Arraylist * r:
ArrayList *createArrayList(int length){
int i=0;//index variables
ArrayList *r=malloc(sizeof(ArrayList);