I have to create a 2-Dimensional array of char pointers. The array will store a list of names and surnames – row 0 will hold names and row 1 will hold surnames. This is the code I have written so far (this file is included in the main file):
#include "myFunction.h"
#include <iostream>
#include <string.h>
using namespace std;
char ***persons;
void createArray(int n)
{
*persons = new char * int[n];
for(int i=0; i<n; i++)
*persons[i]=new char[n];
}
and main calls this function with:
createArray(3);
but when I run it i keep getting “Segmentation Fault” and I have no idea why
How can I fix this?
If you’re using c++, consider using a 2D array of std::string as it’ll be a little cleaner. Also, multi-dimensional arrays are always horrible to work with as they make code unreadable and cause a lot of chaos (as you don’t often get confused by which dimension represents what). So, I strongly urge you to consider using a struct for each person (with 2 fields, first_name and last_name).
Regardless, if you want to go with your approach, here’s how you’d do it: