简体   繁体   中英

Can I use a pointer to traverse an array of strings?

there. I am now studying C++ Primer. When I writing a piece of program something about pointer confused me. The function of the program below is reading strings into a vector and copying the vector into an array of character pointers. For each element in the vector, allocate a new character array and copy the data from the vector element into that character array. Then print the contents of array of strings.

Here is my piece of code:

vector<string> str_vector;
string str_temp;
while(getline(cin,str_temp)){
    str_vector.push_back(str_temp);
}

typedef const char *cptr;
cptr *cptr_array = new cptr[str_vector.size()];

cptr *p = cptr_array;

for(vector<string>::iterator iter = str_vector.begin(); 
    iter != str_vector.end(); iter++,p++){
    *p = (*iter).c_str();
}

cout<<"Output Char Array Element"<<endl;
cptr *q = cptr_array;
while(*q){
    cout<<*q<<endl;
    q++;
}

delete [] cptr_array;

When I run the program it will crash at after output the array of strings. I could use the following code to do the same thing without any crash.

cptr *q = cptr_array;
for(int i = 0; i < str_vector.size(); i++,q++){
    cout<<*q<<endl;
}

I just want to know why the output code above could not work correctly. Thanks a lot, everyone!

while(*q){

You are using *q as the condition. After the array is iterated over, q points to places after the end of the array, accessing *q is illegal.

*q = cptr_array;
while(*q){

Not only will the loop dereference an out-of-bounds q after traversing the array, you can't test with while(q) either because there's no nullptr sentinel at the end of the array. The simplest thing to do is allocate one more element in cptr than you need to hold pointers to all the string values and then set the pointer value of that last element to nullptr ( 0 ).

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