vector::data

Hey,

I am having a weird output after the usage of vector::data:

1
2
3
4
5
6
7
8
9
10
11
12
// Vector includes: [2, 3, 4, 5]

vector<char>::iterator it;
for(it = v.begin(); it != v.end(); it++) {
    cout << *it << endl;
}

char* c = v.data();
cout << "Array:" << endl;
for(int i = 0; i != strlen(c); i++) {
    cout << c[i] << endl;
}


Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
Array:
2
3
4
5
-3
-3
-3
-3
-67


What's wrong with the usage of vector::data here?

PS: You might think I am using the wrong data-type but I am here in need of an array of chars for later usage on another source.
Last edited on
What does arr contain?
vector::data returns pointers to the elements of the vector. Therefore c should include those, however, I do not understand where those negative numbers come from.
Last edited on
¿How he hell are `arr' and `v' related?
If you intend to write `strlen(c)' then you should know that that only applies to null terminated strings.
Yeah, arr is c. Sorry, my mistake. If vector::data is just for null terminated strings, then how would you solve my assignment?
Well why would you want to interate through arr which would appear to be a char[] (i.e. character array) and then read data from your vector? The cha[] i.e. arr appears to hold more data than your vector, you appear to be assuming that both are in sync which they cannot be.

You would either iterate through your vector:

1
2
3
4
for (auto p = v.begin(); p != v.end(); ++p)
{
   cout << *p << endl;
}


Or iterate through your char[]:

1
2
3
4
for (int n = 0; n < strlen(c); ++n)
{
   cout << c[n] << endl;
}


Don't iterate through one and read from the other.
1
2
3
4
5
6
7
8
9
10
// Vector includes: [2, 3, 4, 5]

for ( int x : v ) cout << x << endl;


char* c = reinterpret_cast<char *>( v.data() );
cout << "Array:" << endl;
for (int i = 0; i != v.size() * sizeof( int ); i++) {
    cout << c[i] << endl;
}
@OP: `std::vector' does not use a null terminator, so `strlen( v.data() )' would obviously fail.
You need to ask for the size.
If vector::data is just for null terminated strings, then how would you solve my assignment?

No, vector::data is not just for null-terminated strings.

strlen is just for null-terminated strings.

You're passing a character array into strlen, and it's returning a different value from the one you're expecting, because the character array is not null-terminated. So your loop is iterating a larger range than you expect it to, and is attempting to read characters after the end of the array.
Last edited on
Topic archived. No new replies allowed.