C++/C中如何判断指针数组是否已被填充
假设我有函数
foo(双 * pa)
其中 pa
填充范围为 [0] 到 [100] 或者 pa
仅针对 [0] 进行填充。
我的函数执行以下操作:
foo(双 * pa)
{
IF(pa 是 100 的数组)THEN x[0 到 100] = pa[0 到 100]
ELSE x[0 到 100] = pa[0]
}
Suppose I have function
foo(double * pa)
where pa
is either populated from [0] to [100]
ORpa
is populated for [0] only.
My function does the following:
foo(double * pa)
{
IF (pa is an array of 100) THEN x[0 to 100] = pa[0 to 100]
ELSE x[0 to 100] = pa[0]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
那是不可能的。
pa
未填充,因为它不是数组。按照惯例,它是一个指针,指向数组的第一个元素。但它的类型只是指向 double 的指针
,并且没有关于它是指向单个 double 还是包含 1、10、100 或 1000 个元素的数组的信息。“传统”解决方案是传递两个参数:指针和数组的大小:
That's not possible.
pa
isn't populated, because it is not an array. It is a pointer which, by convention, points to the first element of an array. But its type is simplypointer to double
, and it has no information about whether it points to a single double, or an array of 1, 10, 100 or 1000 elements.The "traditional" solution would be to pass two parameters, the pointer and the size of the array:
问: foo() 如何知道 pa[] 是否是一个 100 的数组?
一般来说,你必须告诉它。例如:
但是,如果您使用 C++ 进行编码,则可以使用 STL 容器,例如向量:
Q: How is foo() going to know whether pa[] is an array of 100?
In general, you have to TELL it. For example:
If you were coding in C++, however, you could use an STL container such as a vector:
给定 foo() 函数参数中的信息,无法找出:
指向的数组中的元素总数pa
为了实现此目的,您需要向 foo() 函数传递额外的参数,以说明总数组有多大,以及已填充多少个元素。
Given the information in the
foo()
function parameters, it is not possible to find out:pa
In order to accomplish this, you will need to pass additional parameters to the
foo()
function that state how big the total array is, and how many elements have been filled in.基于您的 上一个问题,结合这个问题,我认为您可能想要的只是一个重载,请参见这里:
有了这个,您可以使用指针调用 foo ,其中假定它指向一个至少具有以下属性的数组: 100 个值。或者您可以使用单个值来调用它。将两个函数之间的通用功能放在
foo_impl
中,这样就不会重复代码。Based on your previous question, combined with this question, I think what you may want is simply an overload, see here:
With this, you can call foo with a pointer, where it's assumed to be pointing to an array with at least 100 values. Or you can call it with a single value. Put the common functionality between the two functions in
foo_impl
, that way you're not duplicating code.你不能。
foo()
唯一知道pa
是它是一个指针,无论它是否为空指针,如果它为非空,它指向什么。它无法判断它是指向单个对象还是指向数组的第一个元素。如果可能的话,您可能应该使用
foo()
,以便调用者必须传递附加信息:(注意:您应该声明
foo
的返回类型。)You can't. The only thing
foo()
knowspa
is that it's a pointer, whether it's a null pointer or not, and if it's non-null, what it points to. It can't tell whether it points to a single object or to the first element of an array.If possible, you should probably
foo()
so the caller has to pass in additional information:(Note: you should declare
foo
's return type.)