I have already improved my array from this question in order to be created within a class, I also kind of optimized it using std::vector
so it is not allocated on a heap but on a stack and thus it is faster and also I do not have to manage the memory manually.
But I was not able to create a function which would set a value to an element. I got errors like expression must have pointer-to-object type
(when I try to declare my element as int cell
or an array may not have element of this type
(when I try to declare it as int cell[][]) and I get a segmentation error when I try to declare it like this int *cell[]
.
Here is my code
.hpp
#pragma once
#include <iostream>
#include <vector>
class myPlan
{
int slots;
int rows = 3;
int cell[][];
public:
myPlan(int slots);
void setCellValue(int row, int slot, int value)
};
.cpp
#include "myPlan.hpp"
myPlan::myPlan(int slots)
{
this->slots = slots;
std::vector<std::vector<int> > cell(STATUS_N);
for (int i = 0; i < STATUS_N; i++)
{
// declare the i-th row to size of column
cell[i] = std::vector<int>(slots);
}
//Print the array
for (int i = 0; i < STATUS_N; i++) {
for (int j = 0; j < cell[i].size(); j++)
{
cell[i][j] = 0;
std::cout << cell[i][j] << " ";
}
std::cout << "\n";
}
}
void myPlan::setCellValue(int row, int slot, int value)
{
cell[row][slot] = value;
}
main.cpp
#include "myPlan.hpp"
int main()
{
myPlan plan(N_PLAN);
plan.setCellValue(0,2,42);
}
Thank you very much in advance for any help P.S. I hope that this is more optimal than this array, if there was even better optimized version, I would be glad to learn about it.