1

I am a C++ beginner and my task is as follows:

Define and initialise a single-dimensional integer array. Next, define a pointer that points to the first element in the array and passes the pointer to a function.

Using only pointer variables (and looping constructs), print only the array values that are exact multiples of 7 from start to finish to standard output. The only program output should be the numbers, one per line with no white space.

I have tried:

void print_sevens(int* nums, int length)
{
    int array[5] = { 5,8,21,43,70 };
    int* ptr = array;
    int* num = array;
    for (int i = 0; i < length; i++)
    {
        *num++;
        if (num[i] % 7 == 0) {
            cout << num[i] << endl;
        }
    }
}

int main()
{
    int array[5] = { 5,8,21,43,70 };
    int* ptr = array;
    print_sevens(ptr, 5);
}

It compiles but does not output anything.

I am also confused about passing the pointer to a function. Should this be done in the main file or in the function file?

JeJo
  • 20,530
  • 5
  • 29
  • 68
hi_it'sme
  • 49
  • 6

2 Answers2

3

You are creating an additional array in the print_sevens function, which is unnecessary as you already passed the pointer to the first element of the array created in the main()(i.e. array).

Removing that unnecessary array and related codes from the function will make the program run perfectly. (See online)

void print_sevens(int* nums, int length) 
{
    for (int i = 0; i < length; i++) 
    {
        if (nums[i] % 7 == 0) 
            std::cout << nums[i] << std::endl;
    }
}

and in the main you only need to do the follows, as arrays decay to the pointer pointing to its first element.

int main() 
{
    int array[5]{ 5,8,21,43,70 };
    print_sevens(array, 5);
}

Note that,

JeJo
  • 20,530
  • 5
  • 29
  • 68
-1

You are modifying the contents of your array when you do *num++.

ansjob
  • 154
  • 7
  • i tried allocating a pointer to the *num variable then incrementing and printing that out but it just prints memory addresses – hi_it'sme Aug 21 '19 at 23:40
  • `*num++` is just defeference pointer, then increment pointer. Since nothing is being done to the dereferenced pointer the asker could discard the defererence and not notice a thing. All that code's doing is advancing the pointer. Demo: https://ideone.com/z19w0Q – user4581301 Aug 21 '19 at 23:48
  • That is not causing **the** problem, but it is **a** problem. –  Aug 21 '19 at 23:55