指针变量 在数组中定位零

Pointer Variable to Locate the zero in the array

本文关键字:定位 数组 变量 指针      更新时间:2023-10-16

>我正在尝试制作一个代码,该代码尝试使用指针变量扫描数组中的"0",然后将地址设置为数组中具有"0"的空间的地址。不幸的是,我的程序返回 10 作为值,0 作为索引。我真的很感激任何输入来帮助我,我正在尝试在不更改 main 的情况下执行此操作,因此我认为以下代码是不可能的。

int* zerofinder(int array[], int q)
{
int* p = null;    /// default value if there isn't a 0 in the array at 
all
for (int k = q - 1; k >= 0; k--)
{
if (arr[k] == 0)      // found an element whose value is 0
{
    p = arr[k];     // change the value of p
    break;           // stop looping and return
}
}
return p;
}

相反,我认为我必须使用

void zerofinder(int array[], int x, int* p); function to change the pointer? 

按值传递指针。

然后,更改指针指向的位置,但这只会修改本地副本。它不会更改调用函数中指针的值。

您可以使用以下两种方法之一来解决此问题。

  1. 通过引用传递指针。

    void findLastZero(int arr[], int n, int*& p);
    
  2. 从函数返回指针。

    int* findLastZero(int arr[], int n);
    

    这将更改调用函数的方式。而不是使用:

    int* ptr;
    ptr = &nums[0];
    findLastZero(nums, 6, ptr);
    

    您可以使用:

    int* ptr = findLastZero(nums, 6);
    

问题是你没有从函数中返回你想要的值

int* findLastZero(int arr[], int n)
{
int* p = nullptr;    /// default value if there isn't a 0 in the array at all
for (int k = n - 1; k >= 0; k--)
{
    if (arr[k] == 0)      // found an element whose value is 0
    {
        p = &arr[k];     // change the value of p
        break;           // stop looping and return
    }
}
return p;
}

ptr = findLastZero(nums, 6);

有时新手认为指针很特别,但指针也是值,并遵守有关按值传递的通常C++规则。如果将指针传递给函数,则更改函数内指针的值不会影响函数外部的值,就像任何其他类型一样。

看起来像家庭作业/测试/测验。

这个测验的答案是:如果不更改main功能,就无法做到这一点。

为什么?

正如其他人已经告诉您的那样,您需要更改findLastZero签名,要么将p参数类型更改为 int*&int** ,要么从函数返回int*。如果不更改findLastZero签名(和main(,则findLastZero函数无法更改外部ptr变量。