C++ Classes, Pointers, Constructors, Segmentation Faults, 2D arrays

57 Views Asked by At

.h file

public:
Class(int x, int y); //constructor for this question

private:
char (*1dArrayObjectPtr)[size] = nullptr;
char nameof2dArray[notImportantX][size];

What is the difference between initializing Class (*1dArrayObjectPtr)[size] = nullptr; then assigning by:

cpp file

Class::Class(int x, int y) : x(x), y(y) {1dArrayObjectPtr = nameOf2dArray;};

or:

Class::Class(int x, int y) : x(x), y(y), 1DArrayObjectPtr(nameof2dArray) {};

Why does the top option result in segmentation faults and the bottom does not when I access as:

*(*(1DArrayObjectPtr+i)+j) or 1DArrayObject[i][j]

If I pass 1DArrayObjectPtr to a new class will I be able to iterate the same?:

newClass::newClass(char* 1DArrayObjectPtr) : newClassPtr(1DArrayObjectPtr) {};

iterate as *(*(newClassPtr+i)+j) or newClassPtr[i][j]

Or am I changing the 1dpointer from the 2D array into something else and not realizing?

1

There are 1 best solutions below

0
On

Scheff has confirmed semantically, there is no difference. I will look to my constructors for the base class to see if they could be culprit. Thanks Scheff. I tried to mark your comment as a solution, but I may have flagged it by mistake.... :D