简体   繁体   English

查找动态分配的数组的元素数

[英]Finding number of elements of a dynamically allocated array

I have a dynamically allocated array called Deck, composed of Card objects which have two values, suit and number. 我有一个名为Deck的动态分配数组,由Card对象组成,它有两个值,suit和number。

I need to find the number of cards from my deck array, which I declared as so: 我需要从我的deck数组中找到卡片的数量,我声明如下:

deck = new Card[52];

I'm not sure how to determine the amount of elements in the deck if I change the amount of cards in the deck array. 如果我改变卡座阵列中的牌数,我不知道如何确定牌组中的元素数量。 Right now I have: 现在我有:

int size=0;
Card a;
while (a.getNumber() != '/0'){
    size++;
    a = deck[size];
}

where getNumber() is a function that pulls the number value of the card. 其中getNumber()是一个拉取卡片数值的函数。 However when I run the program is says "The program has stopped working" 但是当我运行程序时说“程序已经停止工作”

This is not possible in C++, or C. You need to create a structure: 这在C ++或C中是不可能的。您需要创建一个结构:

struct Deck { int nCards; Card *cards; }

or, better way is use std::vector<Card> , which already does that for you. 或者,更好的方法是使用std::vector<Card> ,它已经为你做了。 If you really don't want a structure, and for some reason do not want to use a vector, allocate a dummy Card pointer and set it to null to mark the end of array: 如果你真的不想要一个结构,并且由于某种原因不想使用向量,请分配一个虚拟卡指针并将其设置为null以标记数组的结尾:

deck = new Card[52+1];
deck[52] = 0;
while (deck[i]) { /* ... */ }

您可能必须将该数字与数组分开存储,执行类似C字符串的操作并使用sentinel值来指示数组的结尾,或者您实际上可以使用C ++编程并使用可以增长和缩小的向量。

I don't get what you mean when you say that the program says " The program has stopped working". 当你说程序说“程序已停止工作”时,我不明白你的意思。 I assume it's some sort of custom exception message. 我假设它是某种自定义异常消息。

However, I see a possibility of a buffer overflow (array index out of bounds exception) in your code.What if all the 52 slots in the array are occupied and then in the 52nd iteration,the value of the size variable turns 52 ,leading to an illegal index access in the deck array (it has been preallocated a set of 52 slots). 但是,我看到你的代码中有一个缓冲区溢出(数组索引超出边界异常)的可能性。如果数组中的所有52个槽都被占用,那么在第52次迭代中,size变量的值变为52,导致到甲板阵列中的非法索引访问(它已经预先分配了一组52个插槽)。

Also, this is certainly not a dynamically allocated array, because you are setting its size right at the initialization step. 此外,这肯定不是动态分配的数组,因为您在初始化步骤中正确设置其大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM