簡體   English   中英

在結構向量中獲取數據作為輸入時的分段錯誤(SIGSEGV)

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

分段錯誤(SIGSEGV)。 鏈接到代碼該代碼給出了分段錯誤錯誤,這是由於輸入用於存儲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;
}

輸入為:

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

問題是您正在訪問向量的邊界之外。 向量為空,但是v[i]嘗試訪問向量中不存在的元素。 因此,程序的行為是不確定的。

我懷疑您可能打算使用將元素計數作為參數的向量構造函數。

這是有效的代碼。 構建向量時,我會指定向量的大小。

    vector<s> v(n);

編譯代碼:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM