【发布时间】:2021-01-16 17:37:14
【问题描述】:
我有一个 structs sth 数组
#define NUM_ELEM 8
typedef struct sth {
int* tab;
int lenght;
} sth;
...
int main(void) {
sth* arr;
function_allocating_memory_and_values(&arr);
...
return 0;
}
代码中也有函数,它接受指向结构数组的指针,并在其中修改数组的元素。
void minor_function(*sth element) {
//Changes something
}
在函数内部,我必须将指针传递给第 i 个元素。在这里,我介绍了我在 cmets 中尝试过的两个选项:
void major_function(sth** array) {
int index = 0; //the value changes later
...
minor_function(array[index]); //the argument was passed to the function without errors, but nothing happened; during debugging, I have seen also segmentation fault;
minor_function( (*array + index)); //It worked
}
我相信,(*array + index) 是指向第 index 个元素的指针。
(*array)[index] 是第 index 个元素。
1) 如果是双指针,array[index] 是什么?为什么它不起作用?
重新分配的相关问题:
major_function内部有减小结构体大小的功能:
void clear(sth* a) { //free would clear more properly in terms of nomenclature, but I want to reuse the pointer
a->tab = realloc(a->tab, NUM_ELEM*sizeof(int));
a->tab[0] = 0;
a->length = 1;
}
它没有返回任何问题 - 直到我将数组的第一个元素,索引 0 传递给函数:
(*array + index) == (*array + 0) == (*array) //It isn't the code from the program, it is an illuatration
然后我得到一个错误:
realloc(): invalid old size
Aborted (core dumped)
我原以为 *array 会指示数组的第一个元素 - 但是,它不会发生。
-
(*pointer)有什么问题?
3) 如何重新分配第一个元素?
非常感谢您的回答和解释。
编辑
我做了一些额外的研究和调试。
这是分配代码:
#define NUMBERS 45
void stworz_zmienne(sth** arr) {
*arr = realloc(*arr, (NUMBERS+3)*(sizeof(sth)));
for (int i = 0; i<=NUMBERS+3; i++) {
sth cell;
cell.tab = NULL;
cell.tab = realloc(kom.komorka, sizeof(int));
cell.length = 1;
cell.tab[0] = 0;
(*arr)[i] = cell;
}
(*arr)[NUMBERS+1].cell[0] = -1;
(*arr)[NUMBERS+2].cell[0] = 1;
}
我发现:
int main(void) {
sth* array = NULL;
function_allocating_memory_and_values(&array);
clear(&array[1]); //without errors
clear(&array[0]); //realloc: invalid old size
我想第一个元素没有正确分配给 realloc,但我不知道是什么原因以及如何解决它。
【问题讨论】:
-
array[index]和(*array + index)不一样我觉得你需要学习指针。 -
贴出实际代码
-
"(*array + index) 是指向第 index 个元素的指针。(*array)[index]",在这里使用
*(*array + index),那将是一个真实的陈述。另外,需要查看function_allocating_memory_and_values(&arr);是如何定义的。请编辑帖子以添加minimal reproducible example。 -
感谢您的建议;我会记住你关于指针的信息。但是,您能否解释一下,为什么我的问题被否决了?在我看来,它显示了我解决问题的尝试。
标签: arrays c pointers struct realloc