mechaadi
mechaadi

Reputation: 938

C++ Arrays and pointers calling types

Just wanted to clear my doubt, i have two codes can anyone tell me what's the difference between them?

Both the codes are compiling without any error but the output of the second code is not correct.

first code:

#include "iostream.h"

using namespace std;

void func(int *ptr, int size) {


  for (int i = 0; i < size; i++)

 {

 ptr[i] *= 2;

    cout << ptr[i] << endl;

  }

}

int main() {

 int arr[] = {6, 8, 9, 6, 9, 9};

  func(arr, 6);

  return 0;

}

output is :

12

16

18

12

18

18

second code :

#include "iostream.h"
using namespace std;

void func(int *ptr, int size) {

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

(*ptr++) *= 2;

    cout << (*ptr++) << endl;

  }

}

int main() {
  int arr[] = {6, 8, 9, 6, 9, 9};

  func(arr, 6);

  return 0;
}

output is :

8

6

9

0

0

0

Upvotes: 1

Views: 102

Answers (2)

Nish
Nish

Reputation: 379

from this part of the code remove one post increment for ptr

(*ptr++) *= 2;

    cout << (*ptr++) << endl;

Upvotes: 2

user2736738
user2736738

Reputation: 30906

You have incremented the pointer twice in for loop . Accessing memory out of bound is Undefined Behavior. In your case you got 0 but the behavior is undefined.

No difference except in second case you are incrementing the pointer twice.

To get correct behavior

for (int i = 0; i < size; i++) {
    (*ptr) *= 2;
    cout << (*ptr++) << endl;
  }

Upvotes: 3

Related Questions