I have the following code
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int age;
} data;
int storage (data **str) {
*str = malloc(4 * sizeof(**str));
(*str)[0].age = 12;
return 0;
}
int main() {
data *variable = NULL;
storage(&variable);
return 0;
}
I took it from a website source. I think I have a misunderstanding about a basic pointer to pointer concept because here in this code, we have a pointer to a struct, variable, and we are passing this to storage function, which expects pointer to pointer of struct type. After memory was malloced, I don't understand this assignment
(*str)[0].age = 12
It was assigned as if, str was of (*)[] type. I dont understand how this assignment works, like str is now a pointer to an array of structs?
&-operator does?a[b]is equivalent to*(a+b), I mean equivalent. The "direction" in which you exchange one of these expressions with the other does not matter. So your belief thata[b]can only be used ifais an array is false. In fact, by the timea[b]is evaluated,ais no longer treated as an array, but as a pointer.ais null pointer thena + 0causes undefined behaviour6.5 Expressions 6 The effective type of an object for an access to its stored value is the declared type of the object, if any. 87) Allocated objects have no declared type.Why would you say that there is an array allocated bymalloc()?