'Read access violation when compiling c++ code

I am trying to use pointer in reading string array,but it occurs an exception. Here is the code:

#include<vector>
#include<string>
#include<iostream>
using namespace std;


int countn = 1;
class Solution {
public:
    string findPrefix(string compa, string& compb,int n) {
        string prefixi;
        for (int i = 0; i < compa.length(); i++) {
            if (compa[i] == compb[i]) {//Exception occurs here
                prefixi.push_back(compa[i]);
            }
            else break;
        }
        countn++;
        string* nxt = &compb;
        nxt++;
        if (countn<=n) {
            prefixi = findPrefix(prefixi,*nxt,n);
        }
        return prefixi;
    }
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();
        string prefix;
        prefix = findPrefix(strs[0], strs[countn],n);
        return prefix;
    }
};

int main() {
    vector<string> str = { "flower", "fly","flip"};
    Solution test;
    string ans = test.longestCommonPrefix(str);
    cout << ans << endl;
}

Exception occurs in line13

Then I checked the auto box and to find that the pointer nxt is pointing to the last string in str vector(string"filp"), I wonder if the pointer is out of boundary, but I do not know how to fix it and make my code work. Help me plz.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source