我有一个 C 结构体,它基本上包含两个名为 List 的 2D 字符数组。一个用于附加项目,另一个用于插入项目。然后使用名为 add_to_array 的外部函数将 C 字符串添加到这些数组。
我遇到的问题是,当我调用 add_to_array 时,一旦它顺利通过,但一旦第二次调用,我就会遇到段错误。通过测试代码,我发现出于某种我无法弄清楚的原因,在调用 add_to_array 后,List 中的 2D 数组仍然为 NULL。我检查了add_to_array的结果,它每次都返回1(成功)。
目标系统/操作系统是 Ubuntu linux。
typedef struct
{
char** appended;
char** inserted;
size_t app_alloc;
size_t app_elem;
size_t ins_alloc;
size_t ins_elem;
}
List;
void init_list(List* list)
{
list->app_alloc = 0;
list->ins_alloc = 0;
list->app_elem = 0;
list->ins_elem = 0;
list->appended = NULL;
list->inserted = NULL;
}
void free_list(List* list)
{
size_t i = 0;
for (; i < list->ins_elem; ++i)
{
free(list->inserted[i]);
}
free(list->inserted);
i = 0;
for (; i < list->app_elem; ++i)
{
free(list->appended[i]);
}
free(list->appended);
}
int add_to_array(const char* in, char** array, size_t* alloc, size_t* elem)
{
if (*alloc == *elem)
{
if (*alloc == 0) *alloc = list_buff;
else *alloc = (*alloc) * 2;
char** _tmp = (char**) realloc(array, (*alloc) * sizeof(char*));
if (!_tmp) return 0;
else array = _tmp;
}
array[(*elem)] = (char*) malloc(strlen(in) + 1);
strcpy(array[(*elem)], in);
(*elem)++;
return 1;
}
int append_list(const char* in, List* out)
{
return add_to_array(in, out->appended, &out->app_alloc, &out->app_elem);
}
int insert_list(const char* in, List* out)
{
return add_to_array(in, out->inserted, &out->ins_alloc, &out->ins_elem);
}
int main()
{
List test;
init_list(&test);
append_list("test", &test);
if (!test.appended)
{
printf("*%s*", "why is test.appended still NULL?");
}
//append_list("wwww", &test);
//insert_list("ffff", &test);
//printf("%s\n", get_element(0, &test));
//printf("%s\n", get_element(1, &test));
//printf("%s\n", get_element(2, &test));
//free_list(&test);
return 0;
}
Output: why is test.appended still NULL?
感谢 David 的建议,我的代码可以正常工作了,更改如下:
int add_to_array(const char* in, char*** array, size_t* alloc, size_t* elem)
{
if (*alloc == *elem)
{
if (*alloc == 0) *alloc = list_buff;
else *alloc = (*alloc) * 2;
char** _tmp = (char**) realloc((*array), (*alloc) * sizeof(char*));
if (!_tmp) return 0;
else (*array) = _tmp;
}
(*array)[(*elem)] = (char*) malloc(strlen(in) + 1);
strcpy((*array)[(*elem)], in);
(*elem)++;
return 1;
}
int append_list(const char* in, List* out)
{
return add_to_array(in, &out->appended, &out->app_alloc, &out->app_elem);
}
int insert_list(const char* in, List* out)
{
return add_to_array(in, &out->inserted, &out->ins_alloc, &out->ins_elem);
}
最佳答案
因为 C 是一种按值传递语言:-)
当你打电话时,你似乎在期待:
add_to_array(in, out->appended, &out->app_alloc, &out->app_elem);
然后做
int add_to_array(const char* in, char** array, size_t* alloc, size_t* elem)
{
....
array = _tmp;
....
对 array
的更改也会更改 out->append
。
如果您希望它以这种方式工作,您必须将指针传递给 out->append
,并使 add_to_array
看起来像
int add_to_array(const char* in, char*** array, size_t* alloc, size_t* elem)
关于c - add_to_array 调用导致 NULL 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10907650/