Segmentation fault

when i input 's' i get 20 random values, but when i input 'b' i get segmentation fault

Ievadiet cik liels būs masīvs 20 vienības (s) vai 25 vienības (b)
b
masiva bus 25 vienibas
Segmentation fault (core dumped)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <time.h>
using namespace std;

int main()
{
srand (time(NULL));

int y;
char x;

cout<<"Ievadiet cik liels būs masīvs 20 vienības (s) vai 25 vienības (b)"<<endl;
cin >> x;

if (x == 's'){
    cout<<"masiva bus 20 vienibas"<<endl;
    int i, masivs[21]; 
    int n;
    for (i = 1; i < 21; i++){
    masivs[i]=(rand()% 9 + 1);
    }
    do
    { 
    n=n+1;
    if (n != 21)
    {
    cout<<masivs[n]<<endl;
    }
    }
    while ( n != 21);
    if (n == 21)
    cout<<"beigas"<<endl;
    return 0;
}
    
if (x == 'b'){
    cout<<"masiva bus 25 vienibas"<<endl;
    int i, masivs[26]; 
    int n;
    for (i = 1; i < 26; i++){
    masivs[i]=(rand()% 9 + 1);
    }
    do
    {   
        n=n+1;
        if (n != 26)
        {
        cout<<masivs[n]<<endl;
        }
    }
    while ( n != 26);
    if (n == 26)
    cout<<"beigas"<<endl;
    return 0;
    }
}
Last edited on
Take a look at line 26 and 47,

n==0;

By using == , you are comparing n and 0 , which will give you an error, because n is uninitialized. Did you mean initialized the variable n with the value of zero? If so, I would try n=0; .

Good luck!
Just FYI, i found a couple of things. I placed a comment to describe them:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	if (x == 's'){
		cout << "masiva bus 20 vienibas" << endl;
		int i, masivs[21];
		int n;
		for (i = 1; i < 21; i++){
			masivs[i] = (rand() % 9 + 1);
		}
		do
		{
			n = 0;  // n is initialized to zero
			n = n + 1; // Then n is initialized to 1, because 1 = 0 + 1.
			if (n != 21) // This will always be true because 1 != 21.
			{
				cout << masivs[n] << endl; // It will output the value of subscript 1 of the array only (i.e. massivs[1])
			}
		} while (n != 21); // It will continue to loop because 1 !=21 .
		if (n == 21) // It will never reach here, because of the above 1 != 21.
			cout << "beigas" << endl;
		return 0;
	}
Last edited on
Looks like the code has changed, but you forget to initialize n (both of them).
Last edited on
@ OP, for us to help you better, avoid to re-edit the initial code with the problem. We will end up repeating ourselves and waste time. If you make changes to the code, then post them in a new post. Thanks
Topic archived. No new replies allowed.