字符指针的 2D 数组 --> 分段错误?
2D array of char pointers --> Segmentation fault?
我必须创建一个二维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];
但我不知道确切的。
我应该说明一下,您应该使用结构数组,而不是多维数组,其中成员为名字和姓氏。
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 在线编译器中的分段C++没有打印消息
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- EASTL矢量<向量<int>>连续的
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?