字符指针的 2D 数组 --> 分段错误?

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

本文关键字:gt 分段 错误 指针 2D 数组 字符      更新时间:2023-10-16

我必须创建一个二维char指针数组。数组将存储姓名和姓氏的列表——第0行保存姓名,第1行保存姓氏。这是我到目前为止写的代码(这个文件包含在主文件中):

#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调用这个函数:

createArray(3);

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

我该如何解决这个问题?

如果您正在使用c++,请考虑使用std::string的2D数组,这样会更简洁一些。此外,多维数组总是很糟糕,因为它们使代码不可读,并导致很多混乱(因为您通常不会对哪个维度代表什么感到困惑)。因此,我强烈建议您考虑为每个人使用一个结构体(有两个字段,first_name和last_name)。

无论如何,如果你想用你的方法,你应该这样做:

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

不要让指针全局化。这句话让我很尴尬……

*persons = new char * int[n];
我不认为那是对的。"*"是多余的。也许吧,对吧?
persons = new char * int[n];

但我不知道确切的。

我应该说明一下,您应该使用结构数组,而不是多维数组,其中成员为名字和姓氏。