【问题标题】:Make pointer point at the end of the array使指针指向数组的末尾
【发布时间】:2015-11-29 18:31:10
【问题描述】:

如何检查指针是否在我的数组末尾? 这是我的代码。如果输入了d,并且指针在末尾,什么都不做;如果没有,请向右移动。

if(d == 'd') 
{
    if (*p != a[6])   //a[6] is the array length // this is where i need help
    {
        ++*p;
        num_mov++;
        print_status(a, *p, num_mov);
    }
    else
        print_status(a, *p, num_mov);
}

【问题讨论】:

    标签: c arrays pointers indexing


    【解决方案1】:

    使用条件

    if ( p != a + 6)
    

    考虑到这个声明

    ++*p;
    

    不会增加指针本身。它增加了指针指向的对象。

    如果你想增加指针本身你应该写

    ++p;
    

    还要检查函数print_status 的第二个参数是否声明为指针。如果是这样,那么你必须写

    print_status(a, p, num_mov);
    

    插入

    print_status(a, *p, num_mov);
    

    【讨论】:

      【解决方案2】:

      使用 p != a+6 来比较指针,因为如果数组中有重复的元素,这会给出更好的答案。

      这将指向结尾。对于最后一个元素,使用 p!=(a+5)

      【讨论】:

      • 感谢您完成了这项工作。
      • 如果我想设置指针指向数组的末尾?