多维数组-->空对象指针

发布于 2024-09-17 07:04:06 字数 2466 浏览 3 评论 0原文

我正在尝试开发一个 C++ 应用程序。应用程序的一部分旨在创建并启动对象的某些属性,然后将对象存储在多维数组中。问题是在创建对象并将对象存储在数组中之后,检索对象值会给我指向 NULL 的指针。

具体实现请参见下面的代码:

Cell** TestMain::convertToMatrix(){

//char[] lengthArr = arra[0];

//int[][] temp
int rowCount = getCurrentRowCount(); // Gives the row count of the multi-dimensional array
int colCount =  getCurrentColCount(); // Gives the column count of the multi-dimensional array

Cell** cellList;

cellList = new Cell*[rowCount];
for (int rowIter=rowCount-1;rowIter>=0; rowIter-- ){
    cellList[rowIter] = new Cell[colCount];
    for (int colIter=colCount-1;colIter>=0;colIter--) {
        Cell *currentCell = new Cell(arra[rowIter][colIter],rowIter,colIter);

        //Calculate weights
        if (0==currentCell->getValue()) currentCell->setWeight(0);
        if (1== currentCell->getValue()) {
            if (isEdge(rowIter,colIter)) {
                currentCell->setWeight(1);
            }
            else {
                //currentCell->setWeight(1 + getMinimumValue(cellList[rowIter+1][colIter]->getWeight(),cellList[rowIter+1][colIter+1]->getWeight(),cellList[rowIter][colIter+1]->getWeight() ) );
                currentCell->setWeight(1 + getMinimumValue(cellList[rowIter+1][colIter].getWeight(),cellList[rowIter+1][colIter+1].getWeight(),cellList[rowIter][colIter+1].getWeight() ) );
            }


        }

        cellList[rowIter][colIter] = *currentCell;
    }
}
return cellList;

} `

以下是稍后在代码中执行检查的代码:

void StrawberryMain::printField(Cell** arrayOfCells) {

int row=0;
int column=0;

int maxRowCount= getCurrentRowCount();
int maxColCount = getCurrentColCount();


for (;row<maxRowCount;row++) {
    Cell *cellArr = arrayOfCells[row];
    for (;column<maxColCount;column++) {
        Cell currentArrayCell = cellArr[column];

        /*if (currentArrayCell==NULL){   // This line throws an error ->No match for ‘operator==’ in ‘currentArrayCell == 0’. Why?  
        printf("Returned Pointer for Cell was NULL");
        }
        else { */

            printf("%s(%s)|", currentArrayCell.getWeight(),currentArrayCell.getValue());
        /


    //}

    printf("\n");


}

}

当我运行该程序时,我在屏幕上打印了一大堆 nulls作为输出。(对于应该存储在数组中的每个对象都有一个 null

我来自 Java 背景(尽管我之前涉足过 QT C++),所以我有点恼火为什么会发生这种情况。尽管我很感激我的答案我很想解释为什么会发生这种情况(或者解释为什么会发生这种情况的链接),因为我真的很想了解该语言的工作原理,

谢谢您的期待。

I am trying to develop a C++ application. Part of the Application is meant to create and initiate some properties of an Object and then store the object in a multi-dimensional array. Problem is after Object creation and storing the objects in the array, retrieving the Object values gives me pointers to NULL.

Please see code below for exact implementation:

Cell** TestMain::convertToMatrix(){

//char[] lengthArr = arra[0];

//int[][] temp
int rowCount = getCurrentRowCount(); // Gives the row count of the multi-dimensional array
int colCount =  getCurrentColCount(); // Gives the column count of the multi-dimensional array

Cell** cellList;

cellList = new Cell*[rowCount];
for (int rowIter=rowCount-1;rowIter>=0; rowIter-- ){
    cellList[rowIter] = new Cell[colCount];
    for (int colIter=colCount-1;colIter>=0;colIter--) {
        Cell *currentCell = new Cell(arra[rowIter][colIter],rowIter,colIter);

        //Calculate weights
        if (0==currentCell->getValue()) currentCell->setWeight(0);
        if (1== currentCell->getValue()) {
            if (isEdge(rowIter,colIter)) {
                currentCell->setWeight(1);
            }
            else {
                //currentCell->setWeight(1 + getMinimumValue(cellList[rowIter+1][colIter]->getWeight(),cellList[rowIter+1][colIter+1]->getWeight(),cellList[rowIter][colIter+1]->getWeight() ) );
                currentCell->setWeight(1 + getMinimumValue(cellList[rowIter+1][colIter].getWeight(),cellList[rowIter+1][colIter+1].getWeight(),cellList[rowIter][colIter+1].getWeight() ) );
            }


        }

        cellList[rowIter][colIter] = *currentCell;
    }
}
return cellList;

}
`

Here is the code that performs the checking later in the code:

void StrawberryMain::printField(Cell** arrayOfCells) {

int row=0;
int column=0;

int maxRowCount= getCurrentRowCount();
int maxColCount = getCurrentColCount();


for (;row<maxRowCount;row++) {
    Cell *cellArr = arrayOfCells[row];
    for (;column<maxColCount;column++) {
        Cell currentArrayCell = cellArr[column];

        /*if (currentArrayCell==NULL){   // This line throws an error ->No match for ‘operator==’ in ‘currentArrayCell == 0’. Why?  
        printf("Returned Pointer for Cell was NULL");
        }
        else { */

            printf("%s(%s)|", currentArrayCell.getWeight(),currentArrayCell.getValue());
        /


    //}

    printf("\n");


}

}

When I run the program I get a whole load of nulls printed on my screen as output.( One null for every object supposed stored in the array

I come from a Java background ( although I have dabbled in QT C++ before) so I am a bit miffed why this is happening. As much as I would appreciate an answer I would value an explanation as to why this happens ( or a link which explains why this happens) as I really want to understand the workings of the Language.

Thanks in anticipation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌上芳菲 2024-09-24 07:04:06

您的代码中有几个问题。

正如评论中已经指出的,您遇到了内存泄漏问题。

if (currentArrayCell==NULL){ // 此行抛出错误 ->No match for 'operator==' in 'currentArrayCell == 0'。为什么?

代码中声明的 currentArrayCell 是一个 Cell 对象。不是指向一个的指针。因此,您不会比较指向的 Cell 是否为 NULL。该行试图比较 Cell == 0 是否存在。并且由于您显然没有定义可以与 Cell 和 0 一起使用的相等运算符,因此编译器会引发该错误。

考虑到这一点,您应该注意到行 Cell currentArrayCell = cellArr[column];
实际上是创建一个 Cell 的副本。这次可能并不重要。但是,如果您编写类似的代码来修改 currentArrayCell,那么您会发现任何更改仅针对本地副本,而不是针对 cellArr 中的元素。

这一行:

printf("%s(%s)|", currentArrayCell.getWeight(),currentArrayCell.getValue());

很可能没有做你想做的事。 s% 表示您必须传递一个字符串(类似于 const char*)。但是,根据您的其他代码,我猜测这些成员函数返回整数。 printf 是一个低级工具,不具备以这种方式在数据类型之间进行转换的能力。您需要对数据类型使用适当的格式说明符(例如 int 的 %d),或者在将值传递给 printf 之前对其进行转换。

因此,当您使用错误的格式说明符时,会发生的情况是 printf 尝试按字节方式将您实际传递的任何内容解释为格式说明符暗示的任何类型。在您的情况下,它试图将整数解释为字符指针。事实上,我很惊讶这并没有导致崩溃,而只是打印空值。

There are several issues in your code.

As already stated in comments, you have a memory leak issue.

if (currentArrayCell==NULL){ // This line throws an error ->No match for ‘operator==’ in ‘currentArrayCell == 0’. Why?

currentArrayCell as declared in your code is a Cell object. Not a pointer to one. So you aren't comparing if a pointed to Cell is NULL. That line is trying to compare if a Cell == 0. And since you apparently haven't defined an equality operator that could work with a Cell and 0 the compiler raises that error.

With that in mind, you should note that the line Cell currentArrayCell = cellArr[column];
is actually creating a copy of a Cell. It may not be important this time. But if you write similar code where you would modify currentArrayCell, then you would find that any changes are only made to the local copy and not to the element in cellArr.

This line:

printf("%s(%s)|", currentArrayCell.getWeight(),currentArrayCell.getValue());

is most likely not doing what you wanted. s% means you must pass a string (meaning something like a const char*). However, based on your other code I'm guessing that those member functions are returning integers. printf is a low level tool and does not have the ability to convert between data types in that manner. You either need to use the appropriate format specifier for the data type (such as %d for int) or convert the values before passing them to printf.

So what happens when you use the wrong format specifier is that printf tries to byte-wise interpret whatever you actually passed as whatever type the format specifier implies. In your case, it's trying to interpret integers as character pointers. I'm actually surprised this isn't causing a crash instead of just printing nulls.

牵你的手,一向走下去 2024-09-24 07:04:06

只是为了给你一个想法

template<typename T>
struct array {
    array(int m, int n) {
        size_[0] = m, size_[1] = n;
        data_.resize(m*n);
    }
    T* operator[](int i) {
        return &data_.front() + i*size_[1];
    }
private:
    stdvector<T> data_;
    size_t size_[2];
};

just to give you an idea

template<typename T>
struct array {
    array(int m, int n) {
        size_[0] = m, size_[1] = n;
        data_.resize(m*n);
    }
    T* operator[](int i) {
        return &data_.front() + i*size_[1];
    }
private:
    stdvector<T> data_;
    size_t size_[2];
};
初见终念 2024-09-24 07:04:06

从您的代码中可以清楚地看出,您是一名从事 C++ 工作的 C 人员,因此根据您的目标,应该注意以下一些类。

Boost 的 ublas 有一个矩阵实现这通常是比创建自己的实现更好的替代方案。

除此之外,至少您应该使用 向量 而不是动态使用创建数组以减少内存泄漏的可能性。

It seems clear from your code that you're a C guy doing C++, so here are some classes that should be aware of in light of your goals.

Boost's ublas has a matrix implementation that would be a generally superior alternative to creating your own implementation.

Baring that, at bare minimum you should probably be working with vectors instead of dynamically created arrays to reduce the potential for memory leaks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文