3

I want to push_back window into vector hashes1, but on doing so after 1st execution size of the vector was one and the element value was fine, but in 2nd execution even before the execution of hashes1.push_back(window); this statement size was still 1 but element value was replaced by the new window value and after the 2nd execution of hashes1.push_back(window); vector size was 2 and both elements were same as the last one(new value in window). Can anyone please help me here ??

vector<char *> hashes1; WS=200, SHIFT=120, FPF=50, windowStart=0; for(int count=FPF ;count && windowStart+WS <length;count--) { for(int i=0; i<WS; i++) window[i] = buffer[windowStart+i]; //addBreakPoint(window, FPF-count); hashes1.push_back(window); windowStart += SHIFT; } 

2 Answers 2

3

I assume window is a char[] or a char* pointing to an char[].

First you push_back window wich is a pointer to the first element of the array. Then the second time the inner loop is executed, window[0] - the first element - is set again and hashes1[0] still points to that very element.

Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted. Thanks for putting words to my thoughts much more eloquently than I could.
2

Its because you are pushing references to the same address onto the vector, and then just changing the value stored at that address.

for(int i=0; i<WS; i++) window[i] = buffer[windowStart+i]; 

This line sets the value stored at each address in the array to buffer[windowStart+i].

hashes1.push_back(window); 

This line then pushes a pointer to the character onto the vector. So basically on each iteration of the loop you are pushing the same value (the address the pointer is pointing to) onto the vector and changing the value stored at that address.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.