二维数组的字符指针 - >分段故障? [英] 2D array of char pointers --> Segmentation fault?

查看:215
本文介绍了二维数组的字符指针 - >分段故障?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个二维的字符指针数组。数组将存储名称和姓氏的列表 - 第0行将保存名称,第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];
}

并且main调用此函数:

and main calls this function with:

createArray(3);

但是当我运行它我不断得到分割故障,我不知道为什么

but when I run it i keep getting "Segmentation Fault" and I have no idea why

如何解决这个问题?

推荐答案

考虑使用std :: string的二维数组,因为它会更清洁一点。此外,多维数组总是可怕的工作,因为他们使代码不可读,并造成很多混乱(因为你不经常被困惑的维度代表什么)。所以,我强烈建议你考虑为每个人使用一个结构体(有2个字段,first_name和last_name)。

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

这篇关于二维数组的字符指针 - &gt;分段故障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆