Top.Mail.Ru
The C++ Community's Journal -- Day
? ?
The C++ Community's Journal -- Day [entries|friends|calendar]
The C++ Community

[ userinfo | livejournal userinfo ]
[ calendar | livejournal calendar ]

Mutable Array Sizes [23 Jun 2007|05:29pm]
So I've been learning some Java for a class. Apparently in Java everything is a "reference" except for really simple things like ints and doubles, which seems to be a kind of lower-class pointer. You can use this to "grow" arrays at runtime, by simply creating a new, larger array, copying all the values from the old array, and setting the reference to the old array so that it refers to the new one instead.

So I thought, hey, C++ arrays are pointers too. Can't I do this in C++?

Apparently not. Setting a pointer-to-a-pointer equal to a double subscripted array yeilds a compiler error, and setting a pointer to a single subscripted array yeilds segfaults. Declaring the variables as arrays (and not pointers) results in more compiler errors. Why doesn't this work? It seems simple enough. Is there any other way to set the size of arrays inside objects during runtime?

This is what I mean:
class Map {
public:
Map (int //etc);
//....
private:
MapSquare **square;
int *someIntArray;
//...
};

Map::Map (int size)
{
MapSquare tempSquare[size][size];
square = tempSquare; // this produces a compiler error

int tempIntArray[size];
someIntArray = tempIntArray; // this produces segfaults when I try to acess the data using array notation
}


ETA: I actually just remembered that a variation on this does work; I once wrote a string manipulation function, but needed to turn the string (of undetermined length) into an array. So I declared a char* variable inside the function and initialized it to string.c_str () without specifying any length. That worked, but it only seems to do so in initialization, not in assignment. E.g.:

string stringManipFunc (string original)
{
char *cString = original.c_str (); // this works
//...
}


ETA2: added code examples
28 comments|post comment

navigation
[ viewing | June 23rd, 2007 ]
[ go | previous day|next day ]
Image