I've been searching on here for some time but, while I could find related questions, I couldn't find the answer I was looking for. I apologize if this has already been asked.
I need structs where I can store an array of integers. I'm doing it in two different ways, I understand pointers and arrays are similar things but not quite the same, but I fail to tell when I can use which one in what way.
I understand how Test2 works. But, when compiling, I don't know the length of the array so I need to use the heap, so Test1. The problem is I can't assign values to the integers in the array array_int inside the Test1 struct. The way I see it, on the lines I commented with "Error", I'm trying to write a 5 on the memory address array_int points to. But since I didn't make it point anywhere, this doesn't work (I get: Use of uninitialized variable of size 8). Correct me if I'm wrong as I'm still trying to learn these concepts.
Once I do (*test1).array_int = px;
, the pointer actually points somewhere and I can write stuff on that direction.
I have the following problem, how would I do to write something on the next direction aka the next integer in the array?
#include <iostream>
struct Test1 {
int* array_int;
};
struct Test2 {
int array_int[5];
};
int main() {
Test1* test1 = new Test1;
Test2* test2 = new Test2;
/*
(*test1).array_int[0] = 5; // Error
(*test1).array_int[1] = 5; // Error
*/
int x = 5;
int * px = &x;
(*test1).array_int = px; // This one works but I can only initialize first position
(*test1).array_int[0] = 22; // Now this works. I think it is because now the pointer is actually pointing somewhere (to x).
(*test2).array_int[3] = 8;
return 0;
}