这是我的代码
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/**************************************************
a is a pointer to an array of strings
b is a string
This function appends b to *a
n is the number of strings currently "held" by *a
**************************************************/
int append(char ***a, char *b, unsigned long n) {
if (a && *a && **a) {
char** tmp = realloc(*a, (n + 1) * sizeof(**a));
if (tmp) {
tmp[n] = b;
*a = tmp;
return 0;
}
}
return -1;
}
void test() {
char *words[7] = { "food", "is", "good", "to", "eat,", "like", "pizza" };
char** a = malloc(1 * sizeof(*a));
for (int i = 0; i < 7; i++) {
append(&a, words[i], i);
int j = 0;
while (j <= i)
printf("%s ", a[j++]);
printf("\n");
}
}
int main() {
test();
return 0;
}
代码总是能够编译并且没有任何警告。可执行文件运行的预期结果在95%的情况下是正确的,但约有5%的时间会出现“分段错误”。我知道错误发生在a[j++]
处,但我不明白为什么。