Home > Blockchain >  How to input to vector correctly in C
How to input to vector correctly in C

Time:04-28

When I try to input to vector by following code,I met segmentation fault as paseted. I defined vector and set N and tried to input vector N elements. What is the root cause of this? if someone has opinion,please let me know. Thanks

#include <iostream>
#include <vector>

using namespace std;
int N;
vector<int> A(N);
int main(){
    cin>>N;
    for(int i=0;i<N;i  ) cin>>A[i];
}
[ec2-user@ip-10-0-1-187 ]$ ./vector_input 
1
1
Segmentation fault

CodePudding user response:

That's because constructor of A is called with N=0. When you input N, it doesn't affect the vector at all. If you really want to keep using globals, then use std::vector::resize but the recommended way would be:

int main(){
    std::size_t n;
    std::cin >> n;
    std::vector<int> A(n);
    for(auto & x : A) std::cin >> x;
}

CodePudding user response:

This happened because N was never initialized and it was used for initiating vector. So, your code produces undefined behavior.

You need to take input first, and then initialize the vector. Also, avoid using using namespace std;. And there's no real need to initialize A and N in a global scope.

NOTE: To avoid undefined behavior further you enable this flag while compiling C programs.

-fsanitize=undefined,address

Code:

#include <vector>
#include <iostream>

int main(void)
{
    int N;
    std::cin >> N;
    std::vector<int> A(N);
    for(auto &i : A)
        std::cin >> i;
    return 0;
}

CodePudding user response:

You could try calling reserve on A with N and then using emplace_back:

#include <iostream>
#include <vector>

int main() {
  int N;
  std::cin >> N;
  std::vector<int> A;
  A.reserve(N);
  for (int i = 0; i < N; i  ) {
    std::cin >> A.emplace_back();
  }
  return 0;
}

CodePudding user response:

The variable N used for initialization is not initialized

int main(){
    int n,a;
    vector<int> vec;
    cin >> n;
    for (int i = 0; i < n; i  )
    {
        cin >> a;
       vec.push_back(a);
    }
}
  •  Tags:  
  • c
  • Related