我刚刚学习 C,有人可以解释为什么下面的代码在打印数组的第一个元素后会产生分段错误吗?
工作代码会是什么样子?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 8
void make(char ***array) {
*array = malloc(ELEMENTS * sizeof(char *));
(*array)[0] = "test0";
(*array)[1] = "test1";
(*array)[2] = "test2";
(*array)[3] = "test3";
(*array)[4] = "test4";
(*array)[5] = "test5";
(*array)[6] = "test6";
(*array)[7] = "test7";
(*array)[8] = "test8";
}
int main(int argc, char **argv)
{
char **array;
make(&array);
int i;
for (i = 0; i < ELEMENTS; ++i) {
printf("%s\n", array[i]);
free(array[i]);
}
free(array);
return 0;
}