指针变量 在数组中定位零
Pointer Variable to Locate the zero in the array
>我正在尝试制作一个代码,该代码尝试使用指针变量扫描数组中的"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?
按值传递指针。
然后,更改指针指向的位置,但这只会修改本地副本。它不会更改调用函数中指针的值。
您可以使用以下两种方法之一来解决此问题。
-
通过引用传递指针。
void findLastZero(int arr[], int n, int*& p);
-
从函数返回指针。
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
变量。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- 指针变量 在数组中定位零
- C++中三维数组的解定位
- 将 std::vector 的缓冲区替换为错误定位的字符数组
- 修改指针后,在c++中取消数组的定位器
- 在数组、流和字符比较中定位
- 将2D数组错误定位为参数会导致内存转储
- 在OpenGL中定位一个对象数组