How to dynamically allocate data struct array with nullptr and struct members?

Viewed 42

I am newly to programming with c++ and I am trying to allocate memory for array of struct. The problem is I don't know the size of elements inside it at compile time. I want the "empty" part to be allocated with null pointers. I run this code below, but there is no the output I expected to be. Could somebody help me?

#include <iostream>
using namespace std;
typedef struct ones{
    int a;
    int b;
}ones;

ones** twoes = nullptr;

int main()
{
    cout<<"Hello World";
    for(int i = 0; i < 5; i++)
    {
        twoes[i]= nullptr;
    }
    
        cout<< "i dont get HERE" << endl;
  
     for(int i = 0; i < 5; i++)
    {  
        twoes[i]= new ones;
        twoes[i]->a = 2;
        cout<< twoes[i]->a <<endl;
    }
    
    return 0;
}
0 Answers
Related