why am i getting segment fault

I am trying to manually enter names in the for loop why am i getting segment fault really confused and how to fix it, thanks in advanced

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  
string names[] = {};
    int amount;

    cout << "enter the amount of names you want to enter" << endl;
    cin >> amount;

    for (int i = 1; i < amount; i++) {
        cout << "enter number " << i << " you wish to put in order (bubble sort)" << endl;
        getline(cin,names[i]);
    }
..............
..........
........
    cout << "before the order of the names the list is shown " << endl;
    
    for (int j = 0; j < sizeof(names); j++) {
        cout << names[j] << endl;
    }
.........
.........
.......
Last edited on
string names[] = {};

This is why. You have a zero-length array with no elements. sizeof(names) will always be zero. You cannot just add elements that you didn't allocate space for in the for loop. Use std::vector instead.
Last edited on
Hello rezy3312,

Since you left out the important part, is this a C or C++ program?

It is usually best to include enough code to be able to compile and test the program. Also the problem could start somewhere else where you are not thinking of.

"sizeof" is a C function and may not return what you need or are expecting. "names.size()" could be what youare looking for.

Andy

How could this be C code?
sizeof(names) gives size of a pointer

while:

sizeof names gives size of array

It's a huge difference!
still same error but i havent messed with vectors in a while still confused sorry....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

vector<string> names;
    int amount;
    string word;

    cout << "enter the amount of names you want to enter" << endl;
    cin >> amount;

    for (int i = 1; i < amount; i++) {
        cout << "enter number " << i << " you wish to put in order (bubble sort)" << endl;
        cin >> word;
        names.push_back(word);
    }

    cout << "before the order of the names the list is shown " << endl;

    for (int j = 0; j < amount; j++) {
        cout << names[j] << endl;
    }

//// still working on bubble sort
Last edited on
sizeof(names) gives size of a pointer

while:

sizeof names gives size of array

It's a huge difference!
No. sizeof is just an operator. (sizeof(names)) and (sizeof names) would both evaluate to the same thing, and in OP's case it's wrong either way. Use names.size() as Andy said.
https://en.cppreference.com/w/cpp/language/operator_precedence

rezy3312, you're still going out of bounds. You only push_back (amount - 1) words, but you try to print (amount) words.
Change the 1 on line 9 to a 0.
<edit: typo>

If you want the first number displayed to be 1, then cout << (i + 1)
Last edited on
thank you everyone it works gonna finish up the code :)
@Ganado
Interesting I misread this somewhere :) thanks!
Topic archived. No new replies allowed.