Hello All,

I am having trouble looping through a 2D array in C++ (should be very easy, but I am just starting C++). At the current moment I have this class file

``````#include "Cube.h"
#include <freeglut.h>
#include <stdio.h>

Cube::Cube(int cx, int cy, int cz , int cubeWidth)
{
int p[] = { { cx, cy, cz }, { cx, cy-cubeWidth, cz }, { cx + cubeWidth, cy - cubeWidth, cz },{cx + cubeWidth, cy, cz},
{ cx, cy, cz - cubeWidth }, { cx, cy-cubeWidth, cz - cubeWidth }, { cx+cubeWidth, cy-cubeWidth, cz - cubeWidth }, { cx+cubeWidth, cy, cz - cubeWidth } };
points = *p;
int faces[] = { { 0, 1, 2, 3 }, { 3, 2, 6, 7 }, { 7, 6, 5, 4 }, {4, 5, 1, 0 }, {0, 3, 7, 4}, { 1, 5, 6, 2} };
}

bool printed = false;
void Cube::drawCube(){
if (!printed){
glBegin(GL_POLYGON);
for (int i = 0 ; i != 24; i++){
printf("%d: %d, ", i, *(points + i));
if (i % 3 == 0)
printf("\n");
}

printed = true;
glEnd();
}
}

Cube::~Cube()
{
}
``````

``````#pragma once
class Cube
{

private:
int *points;//cd array containing all the points of the cube
int points2;
int *faces;

public:
Cube(int, int, int, int);
~Cube();
void drawCube();

};
``````

As you can see, I tried looping through that way, but what the program prints out doesn't make any sense. I am wondering how I can loop through this array, or if there is any way to store the 2D array as an array then that would work too. When I tried that it gave me a "expression must be a modifiable lvalue" error. I can assign them 1 by one, but I am wondering if there is simpler way of defining them.

I would re-think what you are trying to do?

This example of a 'class Cube' may give you some ideas re. a simpler design.

example of a test main file:

``````// cube_test.cpp //

#include "cube.h"

int main()
{
Cube cu( Point(0, 0, 0), 1 );
cu.show();

printf( "Press 'Enter' to continue/exit ... " ); fflush( stdout );
getchar();
}
``````

.h file:

``````// cube.h //

#ifndef CUBE_H
#define CUBE_H

#include <cstdio>

struct Point
{
int x, y, z;

Point( int x=0, int y=0, int z=0 ) : x(x), y(y), z(z) {}

void print() const
{
printf( "(%d, %d, %d)\n", x, y, z );
}
} ;

class Cube
{
public:
Cube( const Point& pt, int cwidth );
void show() const;
private:
int width;
Point corner;
} ;

#endif;
``````

.cpp file:

``````// cube.cpp //

#include "Cube.h"

Cube::Cube( const Point& pt, int cwidth ) : width(cwidth)
{
for( int ix = 0; ix < 2; ++ix )
{
for( int iy = 0; iy < 2; ++iy )
{
for( int iz = 0; iz < 2; ++iz )
corner[ix][iy][iz] = Point( pt.x + ix*cwidth, pt.y + iy*cwidth, pt.z + iz*cwidth );
}
}
}

void Cube::show() const
{
for( int ix = 0; ix < 2; ++ix )
{
for( int iy = 0; iy < 2; ++iy )
{
for( int iz = 0; iz < 2; ++iz )
{
corner[ix][iy][iz].print();
}
}
}
}
``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.