How can I pass a vector variable to a function?

后端 未结 3 1290
一向
一向 2021-01-28 10:17

How can we pass vector variables to a function? I have a vector of char* and a function which will take a char * as an argume

3条回答
  •  太阳男子
    2021-01-28 11:01

    If you need to pass the contents of a std::vector to a function that takes a C array, you can take the address of the first element of the vector:

    void someCfunc(char *);
    
    std::vector somevec;
    // set up the vector ... then:
    someCfunc(&somevec[0]);
    

    HOWEVER - be careful you don't get the C string convention mixed up here! A std::vector will not append a '\0' to the end of the string automatically; you must do that manually. If it's just a byte buffer, you'll need to pass the vector's size separately. And if you're receiving data back into the vector, the C function cannot expand the vector on its own, so it's up to you to ensure the vector is large enough beforehand.

    Note also that this applies only to std::vector and not to other STL containers.

提交回复
热议问题