c++ - 如何使用 int** array = new int*[n]; 实现变量多维数组?
问题描述
我尝试了这种方法,但是当我cout <<vararr[i][j]<<endl;
尝试解决的问题时出现错误-hackerrank
我的代码-
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int* variablesizedarr(int size){
int* arr= new int [size];
for(int i=1;i<size;i++){
cin >>arr[i];
}
/*I believe the problem is when I return the arr array*/
return arr;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q,size;
cin >>n >>q;
int** vararr= new int* [n];
for(int i=0;i<n;i++){
cin >>size;
vararr[i]=variablesizedarr(size);
}
/*now printing the values to the console*/
for(int k=0;k<q;k++){
int i,j;
cin >>i>>j;
cout <<vararr[i][j]<<endl; /* difinetly an error in this line because that's what the compiler say*/
}
// deallocate the array
for(int i=0;i<n;i++){
delete [] vararr[i];
}
delete [] vararr;
return 0;
}
编辑1:我得到的错误 -
Compiler Message
Segmentation Fault
Error (stderr)
Reading symbols from Solution...done.
[New LWP 2655054]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00000000004011f2 in main () at Solution.cpp:32
32 cout <<vararr[i][j]<<endl;
To enable execution of this file add
add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual. E.g., run from the shell:
info "(gdb)Auto-loading safe path"
我知道我可以像其他人一样做到这一点,但我不会那样学习。任何帮助表示赞赏。
解决方案
感谢@nathanpearson,我能够找到错误
int* variablesizedarr(int size){
int* arr= new int [size];
for(int i=1;i<size;i++){
cin >>arr[i];
}
/*I believe the problem is when I return the arr array*/
return arr;
}
这里 i 的初始化应该是 0,而不是 1。我知道这是一个愚蠢的错误,但是 Hackerrank 调试器在解释错误方面非常糟糕,所以我怀疑我的理解。无论如何,这是不使用向量来制作可变多维数组的另一种方法。
再次感谢内森花时间理解我的问题。我真的很感激。
推荐阅读
- jenkins - 如何将 Codeceptjs 与 Jenkins 集成
- c - 如何计算从 1 到 n 范围内 0 或 1 的总出现次数?
- firebase - Cloud Firestore:不同查询的相同文档。是否按分开阅读收费?
- c# - TCP 连接/断开
- java - Spring Boot父启动器依赖覆盖
- angular - Angular Google Maps 缩放仅工作一次,然后您无法更改缩放值
- python - 循环内的熊猫数据框索引
- python - 对for循环中的每一列进行分组并在Python中打印条形图
- elasticsearch - 什么是 ES/Kibana 中的 _score?
- java - Spring Security - 存储库 SocialUser