指向结构中的数组的指针,其中每个字段都是一个动态数组
Pointer pointing to array in a structure with each field as an dinamic array
我正在尝试填充包含在另一个结构中的结构中包含的数组的字段。
以下是结构定义:
struct Team
{
std::string name;
int position;
int **matches;
};
struct Championship
{
Team *teams;
unsigned int size;
};
然后,我在函数中分配内存。
Championship *createChampions(unsigned int n)
{
int i;
Championship *ptrcamp;
ptrcamp = new Championship;
ptrcamp -> size;
ptrcamp -> teams = new Team [n];
ptrcamp -> teams -> name;
ptrcamp -> teams -> position;
ptrcamp -> teams -> matches = new int *[2];
for (i = 0; i < 2; i++)
{
ptrcamp -> equipos -> partidos[i] = new int [n - 1];
}
return ptrcamp;
}`
当我尝试将每个团队的值保存在动态创建的"矩阵"中时,就会出现问题。
void fillcamp(Championship ptrcamp, int n)
{
int i, j, k;
string s;
for (i = 0; i<n; i++)
{
cin >> ptrcamp.teams[i].name;
cin >> ptrcamp.teams[i].position;
cout << ptrcamp.teams[i].name;
cout << ptrcamp.teams[i].position;
for (j = 0; j < 2; j++) // With this I pretend to fill each column.
{
for (k = 0; k < n - 1; k++)// In this step I tried to fill the matrix
{
ptrcamp.teams[i].*(*(matches + k) + j) = -1;
}
}
}
}
所以编译器说:
> Campeonato.cpp(52): error : identifier "matches" is undefined
1> ptrcamp.teams[i].*(*(matches + k) + j) = -1;
我尝试了一切,事实是使用传统的 *var[n] 表示法是不允许的。相反,我可以使用 *(var+n(。
谢谢你们的帮助。
"matches" 是一个字段,而不是变量本身。 您需要用点或箭头表示法作为前缀。 在你的代码中,看起来好像你认为你正在这样做,但事实并非如此;我和编译器看着那行代码一样困惑。
你的意思是:
*(*( ptrcamp.teams[i].matches + k) + j) = -1;
如果我是你,我会简化那行(并给变量明确名称(,以便在取消引用之前更清楚地表明你真正指向的内容。 仅此一项就可能解决您的问题。
相关文章:
- std::向量与传递值的动态数组
- 将数组动态分配到具有指针参数的函数中
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- C++ 我在数组/动态内存方面遇到了一些问题
- C++ 中从数组动态强制转换
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 将数组动态添加到多维数组
- 类中的类数组-动态数组(c++)有问题
- 分配对象数组动态冻结