I'd like to implement a function that selects a random object from an array of objects and returns it to me. It should be something like (in C++ instead of psuedocode):

getRandomObject(objectList) {
    return objectList[int(random(length of objectList))];
}

My current code looks like this, but doesn't seem to work:

//definition of random selector
object getRandomObject(Object* objectList) {
    return objectList[int(ofRandom(0, sizeof(objectList)))];
};

//create a pointer for the listOfObjects
object* listOfObjects;

//create an empty object to put the randomly selected object in
object randomObject;

//later in the code, populate the array:
object* listOfObjects[] = {
    new Object(),
    new Object(),
    new Object()
};

//select random object
randomObject = getRandomObject(listOfObjects);

But this seems to return a segmentation fault. A few problems I've noticed:

sizeof() returns the size of the pointer in getRandomObject, not the size of the array. is there a good way to get the size of the array? It might involves not using a float* pointer for the array. Is this a good use case for vectors?

I think that much of the problem lies in how I'm creating my arrays, and not so much in how I'm selecting the random object from them. I'm relatively new to C++ (coming from a Java background), so much of pointers / references / memory management in general is new to me.

thanks!

有帮助吗?

解决方案

I see one definite problem and one possible one. The definite problem is that sizeof(objectList) returns the size of the objectList pointer, which will be 4 or 8 on most platforms. It does not return the number of elements in the array, objectList. Either pass in the length of the array or use std::vector or std::array.

The second possible problem relates to ofRandom. Make sure that ofRandom(a,b) returns numbers >= a, but strictly < b. If it returns values <= b, then you'll need to us ofRandom(0, objectVector.size() - 1). Typically, functions like this are written to return values strictly < b, but you should check.

其他提示

C++ has an array template class that you may want to consider using. Check out the documentation here: http://www.cplusplus.com/reference/array/array/

This type has a method, size(), that will return the length of the array.

When the sizeof operator is applied to an array, it yields the total number of bytes in that array, not the size of the pointer represented by the array identifier. Quote

So you take the space alocated for your whole array and divide by the memory need just for one element: sizeof(objectList) / sizeof(*objectList).

Mr Fooz noticed issues that cause a segfault.

Other compilation issues are:

listOfObjects is declared with 2 different types: object* and object*[3] while getRandomObject expects a type Object*.

listOfObjects[] contains elements of type object* while getRandomObject reads elements of type Object and returns object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top