hello my c++ prog gives segmentation fault [closed]

  c++, pointers, segmentation-fault

this c++ code:

#include <iostream>

struct vec {
    int size;
    int cap;
    int* arr;
};

void vec_init(vec& v) {
    v.size = 0;
    v.cap = 1;
    v.arr = {0};
}

void push_back(vec& v, int i) {
    if (v.size == v.cap) {
    int arr[2 * v.size];
    for (int ind = 0; ind < v.size; ind++) arr[ind] = v.arr[ind];
    v.arr = arr;
    v.cap *= 2;
    }
    v.arr[v.size++] = i;
}

int get(vec& v, int ind) {
    return v.arr[ind];
}

int main() {
    using namespace std;

    int i;
    vec v;
    vec_init(v);
    while (cin >> i) push_back(v, i);
    for (int ind = 0; ind < v.size; ind++) cout << get(v, ind) << " ";
    cout << endl;
    return 0;
}

when run it:

[email protected] 007 % ./a.out 
1
zsh: segmentation fault  ./a.out
[email protected] 007 % 

Source: Windows Questions C++

LEAVE A COMMENT