简体   繁体   English

如何将数组大小传递给C ++中的函数

[英]how to pass array size to function in C++

just I want to ask how can I pass array size to throw function to set size of my game recoreds the only reason I am not using vector because I will base this recored to PMI lib and it doesn't support C++ Constrainers because it written in C that's why I use array 只是我想问一下如何传递数组大小来抛出函数来设置我的游戏记录的大小我唯一的原因是我不使用向量因为我将这个记录基于PMI lib并且它不支持C ++ Constrainers因为它写的C这就是我使用数组的原因

void playGame(int max_streak_length)
{
    int tracker =0 ;
    const int arrsize  = max_streak_length;

    int gameRecored[arrsize]={0};


    while( tracker < 4)
    {

        Craps games;

        if( games.Play()== true)
        {
            tracker++;
        }
        else
            if(tracker >0)
        {
            gameRecored[tracker-1]++;
            tracker = 0;
        }

    }
    gameRecored[tracker-1]++;
    int v= 0;


}

C++ does not support the variable length array feature available in C.99. C ++不支持C.99中提供的可变长度数组功能。 However, C++ offers std::vector<> which is as easy to use, and some may say safer. 但是,C ++提供的std::vector<>易于使用,有些人可能会说更安全。

    std::vector<int> gameRecored(arrsize, 0);

You can use gameRecored as an array like you do in your current code, and it will clean itself up when the function call returns. 您可以像在当前代码中一样将gameRecored用作数组,并且在函数调用返回时它将自行清理。

you can't not define an array whose size is a VARIABLE. 你不能不定义一个大小是VARIABLE的数组。 If you want a dynamic size, you should use operator new, just like this: 如果你想要一个动态大小,你应该使用operator new,就像这样:

int mysize = 10;
int* array = new int[mysize];

the variable mysize can be a dynamic number, such as function parameter. 变量mysize可以是动态数字,例如函数参数。 If your array will never change its size, you can use : 如果您的阵列永远不会改变其大小,您可以使用:

int array[10];

remember, if you use operator new, you must use operator delete to delete your array when you don't need it. 请记住,如果使用operator new,则必须使用operator delete在不需要时删除数组。

Hop can help you. Hop可以帮助你。

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

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