Note that there are some explanatory texts on larger screens.

plurals
  1. POSegmentation fault when adding a pointer to an array
    primarykey
    data
    text
    <p>I have created two classes, Class and Students. In the Class constructor, I need to initialize an array of pointers (pStudents) to Student objects dynamically (I can't use vectors), initialized to null. When I add a student to the class using the function addStudent, I want to be able to search the array of pointers for the first null address and then assign the student to that spot in the array. If the student is already in the class, I also want to be able to search the array to see if this student is already there.</p> <p>When I try to compile the program, I get a segmentation fault. I know it has to do with the way I am using heap memory when I create the pStudents array, but I am unsure of how to resolve this.</p> <p>Here is how I have declared the array in the Class header file:</p> <pre><code>Student **ptrStudents; </code></pre> <p>This is the constructor for the Class objects. For now, I'm using the arbitrary size 40 for the array.</p> <pre><code>Class::Class() { Student **ptrStudents = new Student*[40]; } </code></pre> <p>Here is the function addStudents, which takes a pointer to a student object as its argument. Note that string name is a data field for all students.</p> <pre><code>Class::addStudents(Student *student) { string name = student -&gt; getName(); string nameTemp; for (int i = 0; i &lt; 40; i++) { if (ptrStudents[i] != 0) { nameTemp = ptrStudents[i] -&gt; getName(); if (name == nameTemp) { cout &lt;&lt; "This student is already in the class." &lt;&lt; endl; return; } } else if (ptrStudents[i] == 0) { ptrStudents[i] = student; return; } </code></pre> <p>And here is the main function I'm working with:</p> <pre><code>int main () { Class Economics; Student student1("Hannah"); Economics.addStudent(&amp;student1); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload