如何解决重新分配结构数组的第一个元素 - 无效的旧大小; (*pointer + 0)
我有一组 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 个元素。在这里,我提出了我在评论中尝试过的两个选项:
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
我想第一个 elementi 没有为 realloc 正确分配,但我不知道是什么原因以及如何解决它。
解决方法
关于第一个问题:
void major_function(sth** array) {
int index = 0; //the value changes later
...
minor_function(array[index]); // fails because pointing to somewhere undefined or not allocated in your case.
// Only array[0] could eventually be use because it is ‘equivalent’ to *array
// nut here it would a bad idea
array 是指向 (pointer or array) 的指针,所以 *array 可以被看作是一个数组,用于访问诸如 (*array)[index] 或最终“*array + index”之类的元素。在 c 中的后一种情况下,对指针或数组的 + 操作将增加数组元素的大小或指针指向的内容。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。