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

问题描述

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

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?

推荐答案



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.


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

07-31 12:11