101 175 123 52 78 184 202 8 219 15 49 254 86 62
156 213 41 200 123 131 252 186 108 116 39 205 243 120
218 239 201 109 52 173 244 58 185 18 64 209 165 222
81 136 247 149 183 206 164 214 179 121 176 200 89 128
61 224 221 103 114 170 88 133 117 30 104 46 19 151
99 111 41 180 188 1 32 27 100 241 97 56 22 10
So I have my school project. I need to read integers from a file and allocate dynamic memory and store those integers. The array rows and columns are growing dynamically as needed. The code is working fine step by step but if I try to randomly access an index of the array, it gives me an erroe. Please help me out
#include<iostream>
#include<fstream>
using namespace std;
int* grow(int* ptr,int& cols, int num);
int** grow(int** ptr,int& size);
int main()
{
int num=0;
int cols=0;
int size=0;
int** mat=nullptr;
int* ptr=nullptr;
ifstream fin;
fin.open("numbers.txt");
string line;
while (getline(fin, line))
{
mat=grow(mat,size);
for(int i=0; i<line.size(); i++)
{
num=0;
while(line[i]!=' ' && line[i]!='\n')
{
num=(num*10)+line[i]-'0';
i++;
}
mat[size]=grow(mat[size],cols,num);
}
cout<<"Size:"<<size<<endl;
for(int i=0; i<cols; i++)
{
cout<<mat[size][i]<<' '; // working fine
}
cout<<endl;
cols=0;
}
cout<<endl<<endl<<mat[2][4]<<endl; //not working
}
int** grow(int** mat,int& size)
{
int** ptr=new int*[size+1];
for(int i=0; i<size; i++)
{
ptr[i]=mat[i];
}
size++;
return ptr;
}
int* grow(int* ptr,int& cols, int num)
{
int* nptr=new int[cols+1];
for(int i=0; i<cols; i++)
{
nptr[i]=ptr[i];
}
nptr[cols++]=num;
return nptr;
}