将指针与数组区分开. [英] Differentiating a pointer from an array.

查看:84
本文介绍了将指针与数组区分开.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以将指针与数组区分开.

Is there any way to differentiate a pointer from an array.

void Fun(int* p)
{
    // For these values to be proper p should be array of two
    // But how to check if p is an array or is a pointer ?
    int i = p[0];
    int j = p[1];
}

void main()
{
    int a[2] = {1, 2};
    Fun(a);

    int* b = new int;
    *b = 1;
    Fun(b);
}



总是有更好的替代方法可以更好地执行此操作.

但是我想知道是否可以区分?



There are always better alternatives to do this in a better way.

But I want to know if we can differentiate?

推荐答案

Fun()中使用的参数始终是指针.在那时还无法知道它是以静态数组还是动态数组开始的生活.区分的唯一方法是在编译时(如Griff所建议的那样),但是在可执行代码中,指针始终(也是唯一)是指针.
The parameter used in Fun() is always a pointer. Whether it started life as a static or dynamic array is impossible to know at that point. The only way to differentiate is at compile time (as Griff suggests), but in the executable code a pointer is always (and only) a pointer.


Fun不可能知道这一点,除非呼叫者将信息传递给它.
通常的方法是(例如,参见 GetWindowText [ ^ ]函数):调用者将指针与缓冲区本身的大小一起传递给缓冲区.
There is no way Fun may know that, unless the caller pass it the information.
The usual approach is (see, for instance GetWindowText[^] function): the caller pass the pointer to the buffer together with the size of the buffer itself.


使用C ++,在堆栈上检测数组非常容易使用模板....但是类型信息在使用前一定不能丢失.如果只想支持数组,则可以删除对指针起作用的第一个函数(或添加一个size参数).

或者,您可以改用std::vector<int>(并具有适当的重载).

With C++, is is quite easy to detect array on the stack using templates.... But type information must not be lost before being used. If you only want to support arrays, then you can delete the first function that works on pointers (or add a size parameter).

Alternatively, you can uses std::vector<int> instead (and have appropriate overload).

void Fun (int *p)
{
    // p is a pointer
}

template <int N> void Fun(int (&p)[N])
{
    // p is an array
}

int main()
{
    int a[5];
    Fun(a);    // Will call second function

    int *p = a;
    Fun(p);    // Will call first function
}



通常,如果代码很复杂,则模板版本应调用带有额外参数的非模板版本,以避免代码膨胀,并保持不必在调用方处显式指定大小的便利.

通常应删除第一个函数(或添加一个额外的大小参数),以免造成无提示的误用.



Generally if the code is complexe, then the template version should call a non-template version with an extra argument to avoid code-bloat and keep the convenience of not having to explicitly specify the size at the caller.

By the way first function should generally be deleted (or an extra size argument added) to avoid silent misuse.


这篇关于将指针与数组区分开.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆