#include<vector>
#include<iostream>
int main(){
std::vector<int*> vektor(3);
int a = 7, b = 3, c = 5;
vektor.push_back(&a);
vektor.push_back(&b);
vektor.push_back(&c);
for(int i = 0; i < 3; i++){
std::cout << *(vektor.at(i)) << " ";
}
return 0;
}
I get an error Quote
Segmentation fault (core dumped)
#include<vector>
#include<iostream>
int main(){
std::vector<int*> vektor(1);
int a = 7, b = 3, c = 5;
vektor.push_back(&a);
vektor.push_back(&b);
vektor.push_back(&c);
for(int i = 1; i < 4; i++){
std::cout << *(vektor.at(i)) << " ";
}
return 0;
}
...it works! But why? I changed the vektor element count from 3 to 1 and changed inside for loop initial value of i from 0 to 1 and from i < 3 to i < 4.How is this working now??? And more importantly, what mistake did I do first time?
Cause I can't see it. I set a vector holding a pointers to int variable and set the element count to 3. Then I put addresses of three int variables to pointers inside vector vektor with push_back() member function.
Since arrays and what not is always starting at index 0 I start to "read" from that index as well. But it doesn't work.
Only until I change element count for vector vektor from 3 to 1 and increase the starting index will it work.
Why is first example not working? :cursing:


Sign In
Create Account


Back to top









