简体   繁体   中英

Passing an array as a function argument in C++

If I have this function:

void initPoints(sf::Vector2f points[]);

Why can I do this:

sf::Vector2f[] vecs = {sf::Vector2f(0,0), etc};
initPoints(vecs);

But can't do this?

initPoints({sf::Vector2f(0,0), etc});

VS gives me an error on the second one, but not on the first one.

By using std::vector or std::array you can resolve your problem easier :) Furthermore, std::vector is RAII-conform, so you don't have to manage the memory by yourself. Generally, STL classes are better than C-type arrays.

#include <vector>
#include <initializer_list>
// ...
std::vector<sf::Vector2f> vecs = { Vector2f(0,0), etc };

Then:

initPoints(const std::vector<sf::Vector2f>& vec) {
    // ...
}
initPoints(vecs);

C++ generally doesn't allow you to pass an actual array as a function parameter. It has a convenience feature that makes you think that's possible, in that you can actually pass a pointer.

In other words:

void initPoints(sf::Vector2f points[]);

Is the same thing as

void initPoints(sf::Vector2f* points);

Note that initPoints doesn't know the length of points , so generally you also pass a length parameter:

void initPoints(sf:Vector2f* points, size_t length);

What you're trying to do simply isn't valid pre-C++11. In C++11 you can overload initPoints() to take a std::initializer_list<sf::Vector2f> , and the syntax will work fine.


The kind of array you're using is often called a "C-style array." It exists in C, and has existed in C++ from the beginning. It has various limitations, such as what you've just run into. It looks like you really want a std::vector . There is some nuance to using std::vector s, and I don't know your level of C++ understanding, so I don't know if the phrases "usually you don't want to pass them by value" or "I would recommend you imitate STL functions and pass begin/end iterators instead" mean anything to you. You will eventually come across the parts of the language that make those statements useful. You don't need to worry about them right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM