1

My question is that if you were print out the resulting *(ary + i), which I know is another way to say ary[i] value, would the following output be a hexadecimal/garbage data or would that specific index be assigned a new value based on the result computed from *ary + i? This whole pointer stuff still throwing me off.

  int ary[] = [7, 5, 3, 1, 2, 4, 6, 8];

  for (int i = 0; i < 8; i++)
        {
            *(ary + i) = *ary + i;
        }
2
  • Please consider indenting your code. Commented Nov 2, 2017 at 7:14
  • ary[i] = ary[0] + i. Commented Nov 2, 2017 at 9:54

2 Answers 2

2

ary decays to a pointer in the expressions you posted. And since it always produces the same address (the first element), *ary will evaluate to 7 at every iteration.

Since you understand that *(ary + i) is equivalent to ary[i], you should now gather that your loop body is akin to this:

ary[i] = 7 + i;
Sign up to request clarification or add additional context in comments.

1 Comment

"*ary will evaluate to 7 at every iteration.", which is true only because first iteration doesn't change that value.
-1

int ary[] = [7, 5, 3, 1, 2, 4, 6, 8]; is wrong assignment method,

one must use { } to assign values to array.

So, correct way to define is: int ary[] = {7, 5, 3, 1, 2, 4, 6, 8};

Here *(ary + i) is equivalent to ary [i] , and *ary + i is equivalent to ary [0] + i.

Addressing your question, no it won't throw hex or garbage, you have dereferenced a pointer, so it will give the data stored at that location.

Code:

#include <iostream>

 int main ()
  {
      int ary[] = {7, 5, 3, 1, 2, 4, 6, 8};
      for (int i = 0; i < 8; i++)
      { 
          *(ary + i) = *ary + i; 
      }

      for (int j=0;j <8;j++)
      {
          std::cout <<ary [j];
       }
    }

Output:

7891011121314

Hope you draw the correlation.

if this helps great, if it doesnot, indicate so in comments, willing to edit

3 Comments

*ary + i is not equivalent to ary [i] + 1 it is equivalent to ary[0] + i(not the downvoter btw)
also Storyteller appears to have given a full and correct answer six minutes before you - but you might have started writing your answer before you saw that.
Yess..it seems...so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.