Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating through a 2D vector using one use case of for loop gives segmentation fault

I needed to write a simple method that calculates the highest element in a matrix data (implemented in this case using a 2D vector). Inside the method, initially, I was accessing each element in the 2D vector using the one form (the most common one) of for loop which gave a "segmentation fault". Unfortunately, I could not find a good reason that it should happen. Eventually, I resolved the issue using for loop in a different manner. However, I would still like to know the cause for the "segmentation fault" in the initial us case of for loop. I believe it is also a correct method to iterate through a 2D vector. Can someone explain the reason for this? Thanks in advance!

Initial(giving the error):

class customers {
public:
    int maximumWealth(vector<vector<int>>& accounts) {
        int richest_customer_wealth = 0;
        int sum;
        for(int i=0;i<accounts.size();++i){
            sum = 0;
            for(int j=0;i<accounts[i].size();++j){
                sum += accounts[i][j];
            }
            if(sum > richest_customer_wealth)
                    richest_customer_wealth = sum;
        }
        return richest_customer_wealth;
    }
};

After modifying the for loop:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class customers{
public:
    int maximumWealth(vector<vector<int>>& accounts) {
        int richest_customer_wealth = 0;
        int sum;
        for(vector<int> row: accounts){
            sum = 0;
            for(int val: row){
                sum += val;
            }
            if(sum > richest_customer_wealth)
                    richest_customer_wealth = sum;
        }
        return richest_customer_wealth;
    }
};

>Solution :

I believe it may be because in the inner loop you have

for(int j=0;i<accounts[i].size();++j)

when it should be

for(int j=0;j<accounts[i].size();++j){
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading