我有一个原型(prototype)为的函数
void test( int array [] , int b);
我知道我们可以将原型(prototype)替换为:void test(int*, int);
在 main()
中,我们声明了以下数组:
int array1[10], array2[10];
要将函数体设置为0,
test ( array1 , b)
{
for ( int i = 0 ; i < b ; i++)
array1[i] = 0;
}
我可以做以下事情吗?为什么?
int main()
{// assuming b is the size of the array
test(array1 , b);
test(array2 , b) ;
return 0;
}
我知道 C++ 的基础知识,我正在尝试编写自己的包含文件。 我只是想知道这是否可能,这是一个不错的选择吗?
最佳答案
不是对您问题的直接回答,但您谈论 C++ 但使用普通的旧 C 数组这一事实引起了我的注意:
首先考虑不使用 C 数组。相反,使用 std::vector<int>
.这可能避免了首先问这个问题的需要(并且避免了很多其他问题)。自 int
以来,您无需担心合适的尺寸类型(size_t
?std::vector
?其他?)已经为您提供了正确的类型:std::vector<int>::size_type
.
你的函数签名就是
void test( std::vector<int> &a );
用零填充 vector 的实现是:
void test( std::vector<int> &a )
{
std::fill( a.begin(), a.end(), 0 );
}
关于c++ - 如何调用C++函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6568300/