1

The question is to find the output of the following program:

#include <iostream>
using namespace std;

int main() {
  int arr[]={6,3,8,10,4,6,7};
  int *ptr=arr,i;
  cout<<++*ptr++<<'@';
  i=arr[3]-arr[2];
  cout<<++*(ptr+i)<<'@'<<'\n';
  cout<<++i+*ptr++<<'@';
  cout<<*ptr++<<'@'<<'\n';
  for(;i>=0;i-=2)
      cout<<arr[i]<<'@';
  return 0;
}

The output for the above program is:

7@11@

6@8@

11@3@

I know when a pointer is used like this : *ptr=&var; it stores the address of the variable var in the pointer variable ptr.

These are my questions:

  1. What does *ptr=arr[]; do? Where ptr is declared as an integer and arr is an integer array?

  2. What does *ptr=a; do if ptr and a are declared as integer variables?

Community
  • 1
  • 1
Sujit
  • 1,377
  • 2
  • 5
  • 16

3 Answers3

2

What does *ptr=arr; Where ptr is declared as an integer and arr is an integer array?

Set ptr to point to first element of array arr. Read more in What is array decaying?

The declarations are these:

int arr[]={6,3,8,10,4,6,7}; // declare array 'arr'
int *ptr // declare pointer to `int` 'ptr'

What does *ptr=a; do if ptr and a are declared as integer variables?

What you say, in code is this:

int ptr, a;
*ptr=a;

which, will produce an error, like this:

prog.cc: In function 'int main()':
prog.cc:4:4: error: invalid type argument of unary '*' (have 'int')
    4 |   *ptr=a;
      |    ^~~
gsamaras
  • 66,800
  • 33
  • 152
  • 256
  • 1
    You are welcome @Sujit, you asked a nice question, +1. Please make sure to read the linked question I provided.. – gsamaras Mar 31 '19 at 15:30
0
  1. int *ptr=arr both declares ptr as an int pointer, and assigns to ptr the address of the first integer in arr.
  2. *ptr=a assigns the value of a to the pointee of ptr, namely to the integer that ptr points to.
Inon Peled
  • 671
  • 3
  • 11
0
  1. *ptr = arr; Gets the address of the first element in arr.
  2. *ptr = a; Assigns the value of a to the integer that ptr is pointing to.
Rietty
  • 999
  • 7
  • 20
  • Be careful about #1, the author of the question forgot to mention that it is actually `int *ptr = arr;` as part of the declaration of `ptr`. – Inon Peled Mar 31 '19 at 15:28