0

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;
}
trincot
  • 317,000
  • 35
  • 244
  • 286
APL2020
  • 85
  • 5
  • I've closed this question as a duplicate. Please study the very detailed information in the duplicate post. Your error is because you did not allocate any memory for your array. It was simply an uninitialized pointer. You only allocated memory for the struct. Your "fix" was to point to a single integer on the stack. That is not the way to do it. Further, in C++ you should avoid the use of raw pointers for arrays in most cases. Use `std::vector`. If you MUST use pointers, consider `std::unique_ptr` or `std::shared_ptr`. – paddy Oct 13 '20 at 23:10
  • Further note: `(*test1).array_int` is the same as `test1->array_int`. Please use the latter. – paddy Oct 13 '20 at 23:11
  • Thank you, this explained it very well ("Your error is because you did not allocate any memory for your array. It was simply an uninitialized pointer"). I'll go read the duplicate post. – APL2020 Oct 13 '20 at 23:15

0 Answers0