指针数组*等级[]
Pointer array *grades[]
我设法将两个不同的数组地址插入指针数组,但当我打印它时,它只给我第一个数组。而不是两者都有:
#include <iostream>
using namespace std;
int *readGrades(int *grades[], int size);
#define SIZE 2
void main()
{
int *grades[SIZE], *length,x;
length=readGrades(grades, SIZE);
for (int i = 0; i < SIZE; i++)
{
x = *(length+i);
for (int j = 0; j < x; j++)
cout << *(grades[i] + j) << endl;
}
}
int *readGrades(int *grades[], int size)
{
int num_grades, count[SIZE],j,x;
for (int i = 0; i < size; i++)
{
cout << "How many grades for student " <<i+1<< "?" << endl;
cin >> num_grades;
cout << "Insert " << num_grades << " gradesn";
grades[i] = new int[num_grades];
for ( j = 0; j < num_grades; j++)
{
cin >> *(grades[i] + j);
x = *(grades[i] + j);
}
count[i] = j;
}
return count;
}
如何打印这两个数组?
您在readGrades
中返回一个int*
count
,当length
被分配时,count
已经被销毁,并且您有一个悬空指针,这会导致在取消引用时出现未定义的行为。停止同时使用指针,并使用std::vector
。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '