У меня возникли проблемы с доступом к объектам, которые я создал в массиве указателей. У меня есть тестовый код, который показывает, что объекты создаются, но в моей функции ShowCluster()
она висит на первой итерации через петлю второго уровня.Не удается получить доступ к объектам, созданным в массиве указателей
Способ, которым я считаю, что он закодирован, заключается в том, что у меня есть объект Node **, который по существу становится массивом 2d. Поскольку я использую оператор new
, мне не нужно беспокоиться о возможности внутри функции.
Любые идеи о том, почему я не могу отобразить содержимое этих объектов, которые я создал. Это всего лишь код игрушки, который я хочу использовать, чтобы помочь понять смысл указателей.
main.cpp
#include <iostream>
#include "Node.h"
void Test(std::string message){
static int testNumber = 0;
std::cout << "[+] Test: " << testNumber << " : " << message << std::endl;
testNumber++;
}
void Default2dNodeArray(Node** myCluster, int height, int width, int vecLength){
Test("Start of array creation.");
myCluster = new Node*[height];
for(int i=0; i<height; i++){
myCluster[i] = new Node[width];
}
Test("End of array creation.");
}
void ShowCluster(Node **myCluster, int height, int width){
Test("Start of Display array.");
for(int i=0; i<height; i++){
Test("Outer for loop");
for(int j=0; j<width; j++){
Test("Inner for loop");
std::cout << myCluster[i][j].myNodeString << " : " << myCluster[i][j].myNodeInt << std::endl;
}
}
Test("End of Display array.");
}
int main(){
int myHeight = 5;
int myWidth =8;
int myVecLength = 4;
Node** myNodeArray;
std::cout << "Starting pointer test" << std::endl;
Test("In main.");
Default2dNodeArray(myNodeArray, myHeight, myWidth, myVecLength);
Test("In main.");
ShowCluster(myNodeArray, myHeight, myWidth);
Test("In main.");
std::cout << "Ending pointer test" << std::endl;
return 1;
}
node.cpp
#include "Node.h"
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
int Node::globalCounter = 0;
Node::Node(){
std::cout << "Node created." << std::endl;
std::stringstream ss;
ss << "Default: " << globalCounter;
myNodeString = ss.str();;
myNodeInt = globalCounter;
myVecLength = new int[3];
globalCounter++;
}
Node::Node(std::string myString, int myInt, int vecLength){
myNodeString = "Non-Default:" + myString;
myNodeInt = globalCounter;
myVecLength = new int[vecLength];
globalCounter++;
}
node.h
#ifndef NODE_H_
#define NODE_H_
#include <string>
class Node {
public:
static int globalCounter;
std::string myNodeString;
int myNodeInt;
int* myVecLength;
Node();
Node(std::string, int, int);
};
#endif /* NODE_H_ */
http://markgodwin.blogspot.com/2009/08/c-reference-to-pointer.html – NDEthos