简体   繁体   English

无法使用指针访问数组中的某些值

[英]Can't Access some values in an array using a pointer

So I was asked to write a program which uses a pointer that points to the first element in an array and pass the pointer to a function. 因此,我被要求编写一个程序,该程序使用一个指向数组中第一个元素的指针,并将该指针传递给函数。 Then using only pointer variables (and looping constructs), print only the array values that are exact multiples of 7. Here's the script: 然后,仅使用指针变量(和循环结构),仅打印7的精确倍数的数组值。这是脚本:

#include <iostream>
using namespace std;

void print_sevens(int *nums,int length){

    for(int i = 0; i < length; i++){

    nums = nums + i;

       if(*nums % 7 == 0)
         cout << *nums << endl;

     }

}


int main() {

   int a[5]={7,49,2,8,70};
   int *p1 = &a[0];
   print_sevens(p1,5);

}

The output from this is : 输出是:

7 7

49 49

-149462114 -149462114

I can't find out what is wrong. 我找不到错误所在。 Any help is appreciated. 任何帮助表示赞赏。 Thanks 谢谢

nums is the pointer to the start of the array. nums是指向数组开头的指针。 You are reassigning it at every loop iteration to be nums + i , not nums + 1 . 您在每次循环迭代时将其重新分配为nums + i ,而不是nums + 1 So, at the fourth iteration, for example, nums points to the initial array start + 0 + 1 + 2 + 3, which is the seventh element in your array of 5 elements. 因此,例如,在第四次迭代中, nums指向初始数组start + 0 + 1 + 2 + 3,这是5个元素数组中的第七个元素。 That's why you get garbage. 这就是为什么你会垃圾。

Use a subscript to make your life easy: 使用下标可以使您的生活变得轻松:

for(int i = 0; i < length; i++){
   if(nums[i] % 7 == 0)
       cout << nums[i] << endl;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM