开发者

2D array of char pointers --> Segmentation fault?

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];
   fo开发者_开发百科r(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:

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];
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜