1

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?

2
  • *persons is going to cause the first segv. Commented Jul 24, 2011 at 15:16
  • You are creating a pointer to a two-dimensional array of chars, something entirely different from a two-dimensional array of char pointers (really!). Which do you want? Commented Jul 24, 2011 at 15:16

3 Answers 3

4

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:

char*** people;

int n = 2;  // two elements, name and surname
int m = 5;  // number of people

people = new char**[m];
for (int i = 0; i < m; i++) {
  people[i] = new char*[n];
}
Sign up to request clarification or add additional context in comments.

1 Comment

oh my word it worked! thank you so much! i've been trying to fix this all day!
0

Don't make pointers global. And I am embarassed with this line...

*persons = new char * int[n];

I don't think that it's right. '*' is extra here. Maybe, it's right?

persons = new char * int[n];

But I don't know exactly.

1 Comment

Or even... persons = new char *[n]
0

I should comment that instead of a multi-dimensional array, it sounds like you should be using an array of structures, with members for first name and surname.

1 Comment

This doesn't answer the question!! He asked about segmentation fault not about how should he design it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.