【发布时间】:2013-05-27 18:53:16
【问题描述】:
typedef struct ArrayList
{
// We will store an array of strings (i.e., an array of char arrays)
char **array;
// Size of list (i.e., number of elements that have been added to the array)
int size;
// Length of the array (i.e., the array's current maximum capacity)
int capacity;
} ArrayList;
以下函数应该为包含结构的头文件支持的字符串数组动态分配内存(见上文):
void panic(char *s)
{
fprintf(stderr, "%s", s);
exit(1);
}
ArrayList *createArrayList(int length){
ArrayList *n = malloc(sizeof(ArrayList));
int initial = 0, i;
if (length > DEFAULT_INIT_LEN)
{
n->array = (char **)malloc(length * sizeof(int*));
n->capacity = length;
for (i = 0; i< n->capacity; i++)
{
n->array[i] = NULL;
}
}
else
{
n->array = (char **)malloc(DEFAULT_INIT_LEN * sizeof(int*));
n->capacity = DEFAULT_INIT_LEN;
for (i = 0; i< n->capacity; i++)
{
n->array[i] = NULL;
}
}
if (n->array == NULL)
panic("ERROR: out of memory in Mylist!\n");
n->size = initial;
printf("-> Created new ArrayList of size %d\n", n->capacity);
return n;
}
然后我有另一个函数应该打印当前在由 createArrayList 函数创建的新分配数组中的所有字符串:
void printArrayList(ArrayList *list)
{
int i;
for(i=0; i<list->capacity; i++)
{
if (list->array[i] == NULL)
printf("(empty list)\n");
else
printf("%s\n",list->array[i]);
}
}
当我在 main 函数中实现 printArrayList 函数(如上)时,输出为:
-> Created ArrayList of size 10
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
但是,如果我在 createArrayList 函数中插入 strcpy(n->array[1], "apple"); 作为测试二维数组保存字符串能力的方法,则输出为:
-> Created ArrayList of size 10
...然后它崩溃了
所以我的问题是我做错了什么?我是否错误地为我的阵列分配内存?我想得到它,所以输出是:
-> Created ArrayList of size 10
(empty list)
apple
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
【问题讨论】:
-
不是主要错误,但您应该分配长度 * sizeof(char*),而不是 length * sizeof(int*)。
标签: c memory dynamic struct allocation