将 vector<char> 传递给指针 char*

use*_*524 3 c++ pointers vector

如何将char向量传递给char *?我知道这个问题可以很容易地用一个带有 SIZE const 的预定义 char[] 数组来解决,但我想要一个向量的灵活性,因为没有预定义的大小。

using namespace std;

//prototype 
void getnumberofwords(char*);

int main() {
    //declare the input vector
    vector<char> input;

    /*here I collect the input from user into the vector, but I am omitting the code here for sake of brevity...*/

    getnumberofwords(input); 
    //here is where an ERROR shows up: there is no suitable conversion from std::vector to char*                     
    return 0;
}

void getnumberofwords(char *str){
    int numwords=0;
    int lengthofstring = (int)str.size();  
    //this ERROR says the expression must have a case

    //step through characters until null
    for (int index=0; index < lengthofstring; index++){
        if ( *(str+index) == '\0') {
            numwords++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*own 6

您可以使用data()member 来获取指向底层数组的指针:

getnumberofwords(input.data());
Run Code Online (Sandbox Code Playgroud)