I am trying to learn better how pointer work in C and pointer to pointer to structure things broke my mind. Here I have 3 questions:
- If I have a structure and a pointer to pointer **tests to this structure (so this is something like an array) how can I use p to access to array members (the best way)? tests[i]->id fails (example of source is below)
- Having that monstrous line with pointers below is something bad to have in the code but I would like to do work with it as well. I think I've mistaken with its template, the output for every next structure's address looks like jumps 32 bytes ahead, while size of structure is only 4 bytes. So in the line I want to (1) take the initial address of the tests top pointer, (2) add to it size of the structure TestCase multiplied by
iso it points to correct array element and (3) add offset of the id field of the structure. And after that I will get address where I can write theidvalue in memory, right? Am I doing this correct? Why *tests value was changed? Buffer overflow?
struct TestCase{ int id; }; int main() { TestCase ** tests; cout << "Size of TestCase: " << sizeof(TestCase) << endl; *tests = (TestCase*)malloc(sizeof(TestCase*)*5); cout << "*tests = " << *tests << endl; for(int i = 0; i < 5; i++) { //*(int*)(tests+sizeof(TestCase)*i+(int)&(((struct TestCase*)NULL)->id)) = i; int addr = tests; // address of structures array in memmory; addr += sizeof(TestCase)*i; //address of current structure; addr += (int)&(((struct TestCase*)NULL)->id); // Adding id parameter offset in memory to current address *(int*)addr = i; // setting id for current structure equal to i cout << (int*)(tests+sizeof(TestCase)*i+(int)&(((struct TestCase*)NULL)->id)) << endl; } cout << "*tests = " << *tests << endl; return 0; }Output is:
Size of TestCase: 4 *tests = 0x600048600 0x23ab90 0x23abb0 0x23abd0 0x23abf0 0x23ac10 *tests = 0x600000000
P.S.: Updated cycle code from one monstrous line to step by step actions.
*tests = (TestCase*)malloc(sizeof(TestCase*));Right here you already are dereferencing an uninitialized pointer.