如果您想要一个大小增加的数组,您别无选择,只能动态分配内存,例如,如果您知道所有字符串将正好有20 个字符:
#define STR_SIZE 20
char* values = NULL;
int nb = 0;
...
// Called every time a string is received
// Here valuesPtr is a char** since we want to change values
void appendStr(char** valuesPtr, int* nb, char* string) {
if (*nb == 0) { // First item
*valuesPtr = malloc(STR_SIZE);
} else { // The size of the array changes : realloc it
*valuesPtr = realloc(*valuesPtr, STR_SIZE * (*nb + 1));
}
if (*valuesPtr == NULL) { // Something went wrong !
perror("malloc/realloc");
exit(1);
}
// Copy the new string at the right place
memcpy(*valuesPtr + STR_SIZE * (*nb), string, STR_SIZE);
*nb++;
}
在其余代码中,访问第 n 个字符串是这样完成的:
values + (STR_SIZE * nb)