【发布时间】:2016-12-08 22:04:27
【问题描述】:
我是 C 新手,我想创建一个动态数组来存储字符串。我为它写了下面的代码,但它没有用。数组元素包含一些 ASCII 字符而不是字符串。
我希望historyArray[0] 的值为"foo"。我该怎么做?
typedef struct {
char *historyCommand;
int usedSize;
int maximumSize;
} HistoryArray;
void CreateHistoryArray(HistoryArray *HistoryArray) {
HistoryArray->historyCommand = (char *) malloc(sizeof(char) * MAX_LEN);
HistoryArray->usedSize = 0;
HistoryArray->maximumSize = INITIAL_SIZE;
}
void ExpandHistoryArray(HistoryArray *HistoryArray, int newSize) {
int *newArray = (char *) malloc(sizeof(char) * newSize);
memcpy(newArray, HistoryArray->historyCommand, sizeof(char) * HistoryArray->maximumSize);
free(HistoryArray->historyCommand);
HistoryArray->historyCommand = newArray;
HistoryArray->maximumSize = newSize;
}
void AddHistoryValue(HistoryArray *HistoryArray, char historyCommand[]) {
strcpy(HistoryArray->historyCommand[HistoryArray->usedSize], historyCommand);
HistoryArray->usedSize++;
if (HistoryArray->usedSize == HistoryArray->maximumSize) {
ExpandHistoryArray(HistoryArray, HistoryArray->maximumSize * 2);
}
}
void freeHistoryArray(HistoryArray *a) {
free(a->historyCommand);
a->historyCommand = NULL;
a->usedSize = 0;
a->maximumSize = 2;
}
HistoryArray historyArray;
【问题讨论】:
-
请提供minimal reproducible example。您如何调用以及调用哪些函数? “我希望 historyArray[0] 的值为“foo”。这没有意义。
historyArray[0]不是char数组。请在描述中更准确。请使用适当的缩进格式化代码可读。 -
char *HistoryArray不是一个字符串数组,它是一个字符数组,它只是一个字符串。 -
BTW,malloc + memcpy + free与realloc相同。 -
编译器不会警告您
strcpy()行中的参数类型错误吗?