I have an array of 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;
}
There are also in code functions, which take pointer to pointer to the array of structs and inside them the elements of the array are modified.
void minor_function(*sth element) {
//Changes something
}
Inside the function, I have to pass the pointer to the i-th element. Here I present two options I have tried with comments:
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
}
As I believe, (*array + index)
is the pointer to the index-th element.
(*array)[index]
is the index-th element.
1) What is array[index]
in case of a double pointer? Why it did not work?
The related problem with the reallocation:
There is the function to decrease the size of the structure inside the 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;
}
It has not returned any problems - until I have passed the function the first element of an array, the index 0:
(*array + index) == (*array + 0) == (*array) //It isn't the code from the program, it is an illuatration
Then I got an error:
realloc(): invalid old size
Aborted (core dumped)
I would have thought, that *array would indicate the first element of the array - however, it does not happen.
- What is the problem with
(*pointer)
?
3) How to reallocate the first element?
I would really appreciate your answers and explanation.
EDIT
I have done some additional research and debugging.
Here is a code for allocation:
#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;
}
I have found that:
int main(void) {
sth* array = NULL;
function_allocating_memory_and_values(&array);
clear(&array[1]); //without errors
clear(&array[0]); //realloc: invalid old size
I suppose that the first elementi is not allocated properly for realloc, but I don't know what is the cause and how to fix it.