简体   繁体   中英

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

.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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM