Tilted Forum Project Discussion Community

Tilted Forum Project Discussion Community (https://thetfp.com/tfp/)
-   Tilted Technology (https://thetfp.com/tfp/tilted-technology/)
-   -   [c++] Array bounds. (https://thetfp.com/tfp/tilted-technology/85448-c-array-bounds.html)

CSflim 03-15-2005 12:10 PM

[c++] Array bounds.
 
I am coming to C++ from java.

What is the best way to pass arrays to functions when the size of the array is not known at compile time?
What about multidimensional arrays?

In java I can write a function for a class like so
public void foo(int[] myarray)

and in that function I can use:
myarray.length
to determine the bounds of the array, so it could be indexed with, say, a for loop:
for(int i=0; i<myarray.length; i++)

in c++ if the size of the array is not known at compile time, I have to use:
void myclass::foo(int *myarray)

if I don't know the size of the array I would have to include it
void myclass::foo(int *myarray, int size)

if I want to pass a two dimensional array:
void myclass::foo(int **my2Darray, int i, int j)

is there a better way to do this?

there is a potential danger in writing to my2Darray[x][y] as the user of the class may have provided incorrect values for i and j. What is the general convention in this regards? Should the writer of the function assume that the supplied values are valid?


I don't have a specific problem as such. I'm just wondering what is the best way to do things and what the accepted conventions are.


EDIT:
also, if I am using an int**, when I am finished with it, how do I delete it?
do I have to do:

for(int i=0; i<n; i++){
delete[] my2Darray[i];
}
delete[] my2Darray;


Using references to references (int**) seems quite a messy way to handle two dimensional arrays, especially compared with int[][].
Is there a better way to implement arrays when you don't know the size at compile time? Any general hints/tips on managing these?

n0nsensical 03-16-2005 08:24 PM

That is pretty much all you can do with C-style arrays. I highly recommend using STL vectors.

#include <vector>

std::vector<int> v; // v is a vector of ints size 0
v.resize(5); // v is now a size 5 vector of ints
v.size(); // returns the size of v (5 in this case)

std::vector<float> u(10); // u is a size 10 vector of floats

(you can leave out the std:: if you are doing either using namespace std; or using std::vector;)

To pass a vector to a function, unless you want that function to have a copy of the original vector, pass a pointer to it or a reference (I recommend references unless you need the pointer functionality):

void foo(std::vector<int> &v)
{
cout << v[0] << endl;
}

You can use a vector of vectors as a replacement for multidimensional arrays, but be careful because every vector has to be resized properly (which I guess you have to do for multidimensional arrays created with new anyway):

std::vector<std::vector<int> > matrix; // you NEED the space between the two >s
// if you want rows rows and cols columns:
matrix.resize(rows);
for (int r = 0; r < rows; ++r)
matrix[r].resize(cols);

Once you've done that you can just do matrix[0][1] etc. as usual to index it.

Going back to C-style arrays, be careful with terminology. int** is a pointer to a pointer, not a reference to a reference (the syntax for pointers is from C while references are only in C++). In fact, it is impossible to have a reference to a reference. How to delete a int** depends entirely on how the memory was allocated. Basically, delete should be called on the same type as new returned, so if you have:
int * x = new int;
int ** px = &x;
You would do delete *px; to free that memory
or in this case:
int * array = new int[6];
int ** parray = &array;
delete [] *parray;
or:
int ** matrix = new int*[6];
for (int r = 0; r < 6; ++r)
matrix[r] = new int[5];
yes, you would do like in your example to free it.

CSflim 03-17-2005 10:26 AM

Thanks for your help.
I've used vectors before and found them very useful. I never thought of using vectors of vectors!

kel 03-17-2005 12:51 PM

It depends on the situation, but you can have arrays of pointers to objects and leave the last position as null so it works like a c-string. You can also encapsulate the array in a struct with a size element. If the array points to structs your defining then you can work in some way to have one of those structs be an end marker of the array.

Generally you should just use a data structure that does this for you and not worry about how large or small it is.

n0nsensical 03-17-2005 11:37 PM

Another nice thing about vectors is they do bounds checking for you, so you can avoid accidental overflows (and intentional overflows by people you don't want intentionally overflowing), also why it's good to use STL strings instead of char arrays.

skaven 03-18-2005 01:07 AM

kel's idea is pretty good if you're forced to use C-style arrays. Simply use something other than a for-loop to iterate over the array:

Code:

int x = 0;
while(your_array[x] != NULL) {
    // do something with your_array[x]
    x++;
}

Of course this requires that you be unusually vigilant about ensuring that the NULL is always present at the end of the array. If you accidentally write a value to the last value of the array, the code will work fine until it hits one of these while loops, at which point you'll exit the bounds of the array (and probably segfault).

CSflim 03-18-2005 06:46 AM

Quote:

Originally Posted by kel
It depends on the situation, but you can have arrays of pointers to objects and leave the last position as null so it works like a c-string. You can also encapsulate the array in a struct with a size element. If the array points to structs your defining then you can work in some way to have one of those structs be an end marker of the array.

Generally you should just use a data structure that does this for you and not worry about how large or small it is.


That's another good idea. Thanks kel.

Rangsk 03-23-2005 11:35 PM

Quote:

Originally Posted by skaven
kel's idea is pretty good if you're forced to use C-style arrays. Simply use something other than a for-loop to iterate over the array:

Code:

int x = 0;
while(your_array[x] != NULL) {
    // do something with your_array[x]
    x++;
}

Of course this requires that you be unusually vigilant about ensuring that the NULL is always present at the end of the array. If you accidentally write a value to the last value of the array, the code will work fine until it hits one of these while loops, at which point you'll exit the bounds of the array (and probably segfault).

This doesn't work if 0 is an allowed value in the array. It's really only valid for strings.

Generally when working with arrays, you have to pass the size of the array.

As for 2d arrays, to create one of dynamic size you have to do this:

Code:

int ** my2darray = new (int*)[x_size];
for (int c = 0; c < y_size; c++)
{
  my2darray[c] = new int[y_size];
}

And so to delete it:
Code:

for (int c = 0; c < y_size; c++)
{
  delete my2darray[c];
}
delete my2darray;

As for vectors, I highly recommend looking a few things:
push_back()
iterators

Let's say T is a type and I have:
vector<T> myVector;

At the start, myVector.size() is 0 since it has no values.
I can add values of type T to end of the vector with:
myVector.push_back(value);

Now let's say I want to loop through all the elements in the vector. The most efficient way is to use iterators:
Code:

for (vector<T>::iterator i = myVector.begin(); i != myVector.end(); i++)
{
  // (*i) contains the current value.  You can basically treat i as a pointer
}

You can also make a reverse_iterator:
Code:

for (vector<T>::reverse_iterator i = myVector.rbegin(); i != myVector.rend(); i++)
{
  // This loops through the vector backwards
}

Have fun :)

Alita 03-30-2005 06:23 PM

do not confuse references

void foo (int &name);

with pointers

void foo (int *name);

Aside from that, you pretty much went over all you can do with C++ in the matter (save for using containers such as vectors, etc).

references are marginally better (check Stroustrup for details), but that's what you have to play with.


All times are GMT -8. The time now is 06:17 AM.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360