简体   繁体   中英

Segmentation Fault (SIGSEGV) when getting data as input in the vector of struct

Segmentation Fault (SIGSEGV). Link to code The code gives Segmentation fault error due to the input taken to store the values for vector of struct.

#include<bits/stdc++.h>
using namespace std;
struct s{
    int a;
    int d;
};

int main(){
        int n;
        cin>>n;
        vector<s> v;
        for(int i=0;i<n;i++){
             cin>>v[i].a;
        }
        for(int i=0;i<n;i++){
             cin>>v[i].d;
        }
    return 0;
}

Input is:

6
900  940 950  1100 1500 1800
910 1200 1120 1130 1900 2000

The problem is that you're accessing the vector outside of its bounds. The vector is empty, but v[i] tries to access elements of the vector that don't exist. Therefore the behaviour of the program is undefined.

I suspect that you may have intended to use the vector's constructor that takes a count of elements as an argument.

Here is the code that works. I specify the size of the vector when I construct it.

    vector<s> v(n);

Compile code:

#include<bits/stdc++.h>
using namespace std;
struct s{
    int a;
    int d;
};

int main(){
        int n;
        cin>>n;
        vector<s> v(n);
        for(int i=0;i<n;i++){
             cin>>v[i].a;
        }
        for(int i=0;i<n;i++){
             cin>>v[i].d;
        }
    return 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