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]);
}
}
當我實現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
...然後崩潰
所以我的問題是我做錯了什麼?我是否錯誤地爲我的數組分配了Memeory?我想要得到它,因此輸出爲:
-> 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)
不是主要的錯誤,但你應該分配length * sizeof(char *),而不是length * sizeof(int *)。 – jarmod