【发布时间】:2015-03-20 16:03:07
【问题描述】:
毕业后我正在学习 C 并尝试更新旧技能。我目前正在尝试制作一个由动态分配的字符串组成的动态分配的数组。下面是我的代码,我正在尝试向先前初始化的数组添加一个形容词,该数组的第一个成员为 NULL。最后一个成员应始终为 NULL。
char **addAdjective(char **array, const char *adjective)
{
int i = 0;
int count = 0;
while (*array != NULL){
array++;
count += 1;
}
array = (char**) realloc(*array, sizeof(*array) * (count+2));
int adjectiveLength = strlen(adjective);
array[count] = (char*) malloc(sizeof(const char)*(adjectiveLength + 1));
for (i = 0; i < adjectiveLength; i++){
array[count][i] = adjective[i];
}
array[count][i+1] = '\0';
array[count+1] = NULL;
return array;
}
当我用以下方式调用上述内容时:
adjectives = addAdjective(adjectives, "beautiful");
adjectives = addAdjective(adjectives, "ugly");
adjectives = addAdjective(adjectives, "sweet");
似乎有什么问题,因为当我尝试打印数组时,我什么也没得到..
可能出了什么问题?
编辑:
打印功能应该没问题:
void printAdjectives(char **adjectives)
{
if (!adjectives)
return;
while (*adjectives) {
printf("%s ", *adjectives);
adjectives++;
}
printf("\n");
}
以及初始化:
char **initAdjectives(void)
{
char **adjectives = (char **)malloc (1 * sizeof(char *));
*adjectives = NULL;
return adjectives;
}
【问题讨论】:
-
你应该也包括打印功能,那里可能有一个错误。
-
还有,
adjectives最初是怎么分配的?