数组作为参数
我创建了一个数组:
CString* pstrArray = new CString[nMySize];
现在如何将它传递给要填充的函数?实际参数是多少?
void FillThisArray(what goes here?)
{
}
I have created an array:
CString* pstrArray = new CString[nMySize];
Now how can I pass it to a function to be filled up? What is the actual parameter?
void FillThisArray(what goes here?)
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该使用容器类: CStringArray
如果你不想要这个(我没有看到任何可能的原因,但无论如何):
You should use a container class: CStringArray
If you don't want this (I don't see any possible reason, but anyway):
为了简单起见:
最明显的接口是:
退后一步:
CString
的所有内存都将由您的 应该考虑使用std::vector
std::vector
因为:push_back()
添加字符串,内存使用量会逐渐增加,并且在这种情况下,内存使用量可能会超出初始大小,而无需您进行任何特殊工作向量
时主动为 nMySize 字符串预留空间和/或创建它们std::string
因为:For simplicity:
The most obvious interface is:
Taking a step back:
CString
s will be allocated by that single new statementstd::vector<std::string>
std::vector
because:push_back()
, and in such usage can grow beyond the initial size without any special work on your partvector
if you really want that behaviourstd::string
because:如果有充分的理由不能使用标准容器类,请考虑采用迭代器样式的方法。这将使您不必担心函数中的数组有多大:
您甚至可以模板化您的函数,以便它不与 pstrArray 的(有问题的)实现相关联:
If there's a very good reason why you cannot use a standard container class, consider taking an iterator-style approach. This would save you having to worry about how big the array is in your function:
You could even template your function so that it is not tied to the (questionable) implementation of pstrArray:
您需要将指针传递给第一个元素以及可用元素的数量:
You need to pass the pointer to the first element, and the number of available elements:
您必须将动态分配的数组作为指向其第一个元素的指针传递。有两种语法,两者都是等效的:
或者
您可以在函数内使用 strArray 参数作为数组。请注意,指针不保存有关数组实际大小的信息,因此如果该大小不是全局可用的,您应该将该大小作为第二个参数传递。哈
You must pass a dymanically allocated array as a pointer to its first element. There are two syntaxes for that, both are equivalent:
or
you can use the strArray parameter as an array inside the function. Please note that the pointer doesn't hold information about your array's actual size, so if the size is not globally available you should pass the size as the second parameter. hth
你不能这样做吗?
Can't u do this?