Difference in printing out pointer value vs arrayWhat is the difference between #include <filename> and #include “filename”?How to initialize all members of an array to the same value?With arrays, why is it the case that a[5] == 5[a]?How do function pointers in C work?Improve INSERT-per-second performance of SQLite?Why does a function with no parameters (compared to the actual function definition) compile?how to increment index of array of pointer values?Dereferencing pointer to entire arrayWhy isn't this pointer arithmetic allowed in C?Passing an array as double pointer in c warning message

Famous conjecture or unsolved problem that could be plausibly proven/solved by freshman mathematician?

Is it unsafe to remove one stud from a load bearing wall?

Meaning of "Nur so anbei."

Why does Smaug have 4 legs in the 1st movie but only 2 legs in the 2nd?

Does quickening a spell change the kind of action it grants?

Why do the US media keep claiming that Iran is violating their nuclear deal even though the deal was withdrawn by the US?

Hands-on murderer

Effects of quantum computing on parallel universes

Was the whistle-blower's (12 Aug 2019) complaint deemed credible?

An historical mystery : Poincaré’s silence on Lebesgue integral and measure theory?

Ball-passing game with a surprise ending

SD Card speed degrading and doesn't work on one of my cameras: can I do something?

A professor commented that my research is too simple as compared to my colleagues. What does that mean about my future prospects?

50k job is offering 90k worth of shares. Scam?

Understanding how List head works

How do the Martian rebels defeat Earth when they're grossly outnumbered and outgunned?

vim: (E)dit anyway without prompting

Why is it “Cat in the Hat”?

Are there "fewer independent theaters than ever"?

Possible executive assistant job scam

What is the meaning of "Ya con hotra y como se yama mijo"?

Pi to the power y, for small y's

Can "marriage" be used as a verb?

Improving the observation skill & making less blunders



Difference in printing out pointer value vs array


What is the difference between #include <filename> and #include “filename”?How to initialize all members of an array to the same value?With arrays, why is it the case that a[5] == 5[a]?How do function pointers in C work?Improve INSERT-per-second performance of SQLite?Why does a function with no parameters (compared to the actual function definition) compile?how to increment index of array of pointer values?Dereferencing pointer to entire arrayWhy isn't this pointer arithmetic allowed in C?Passing an array as double pointer in c warning message






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









9

















I have a question on printing out pointer value and array.



int arr[5] = 1, 2, 3, 4, 5 ;
int * ptr = arr;

for (int i = 0; i < 5; i++)
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));



Above is what I typed in first but it didn't work. So I erased the printf line and entered a new code which is this. And it worked.



for (int i = 0; i < 5; i++) 
printf("%d ", arr[i]);



I understand why the second one worked but still don't understand why first one didn't.



Expected output was 3 4 5 6 7 but the actual output of the first code was
2 3 4 5 -858993460










share|improve this question























  • 2





    You're incrementing the ptr in wrong location. Increment it either in the for loop (i++, ptr ++) or after printf.

    – Antti Haapala
    Jul 17 at 9:29


















9

















I have a question on printing out pointer value and array.



int arr[5] = 1, 2, 3, 4, 5 ;
int * ptr = arr;

for (int i = 0; i < 5; i++)
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));



Above is what I typed in first but it didn't work. So I erased the printf line and entered a new code which is this. And it worked.



for (int i = 0; i < 5; i++) 
printf("%d ", arr[i]);



I understand why the second one worked but still don't understand why first one didn't.



Expected output was 3 4 5 6 7 but the actual output of the first code was
2 3 4 5 -858993460










share|improve this question























  • 2





    You're incrementing the ptr in wrong location. Increment it either in the for loop (i++, ptr ++) or after printf.

    – Antti Haapala
    Jul 17 at 9:29














9












9








9








I have a question on printing out pointer value and array.



int arr[5] = 1, 2, 3, 4, 5 ;
int * ptr = arr;

for (int i = 0; i < 5; i++)
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));



Above is what I typed in first but it didn't work. So I erased the printf line and entered a new code which is this. And it worked.



for (int i = 0; i < 5; i++) 
printf("%d ", arr[i]);



I understand why the second one worked but still don't understand why first one didn't.



Expected output was 3 4 5 6 7 but the actual output of the first code was
2 3 4 5 -858993460










share|improve this question

















I have a question on printing out pointer value and array.



int arr[5] = 1, 2, 3, 4, 5 ;
int * ptr = arr;

for (int i = 0; i < 5; i++)
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));



Above is what I typed in first but it didn't work. So I erased the printf line and entered a new code which is this. And it worked.



for (int i = 0; i < 5; i++) 
printf("%d ", arr[i]);



I understand why the second one worked but still don't understand why first one didn't.



Expected output was 3 4 5 6 7 but the actual output of the first code was
2 3 4 5 -858993460







c






share|improve this question
















share|improve this question













share|improve this question




share|improve this question








edited Jul 17 at 9:18









January

11.4k4 gold badges35 silver badges57 bronze badges




11.4k4 gold badges35 silver badges57 bronze badges










asked Jul 17 at 9:13









jieunjieun

543 bronze badges




543 bronze badges










  • 2





    You're incrementing the ptr in wrong location. Increment it either in the for loop (i++, ptr ++) or after printf.

    – Antti Haapala
    Jul 17 at 9:29













  • 2





    You're incrementing the ptr in wrong location. Increment it either in the for loop (i++, ptr ++) or after printf.

    – Antti Haapala
    Jul 17 at 9:29








2




2





You're incrementing the ptr in wrong location. Increment it either in the for loop (i++, ptr ++) or after printf.

– Antti Haapala
Jul 17 at 9:29






You're incrementing the ptr in wrong location. Increment it either in the for loop (i++, ptr ++) or after printf.

– Antti Haapala
Jul 17 at 9:29













6 Answers
6






active

oldest

votes


















9



















int arr[5] = 1, 2, 3, 4, 5 ;
int * ptr = arr;

for (int i = 0; i < 5; i++)
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));



The reason is you are incrementing the pointer first and then printing its content.



Perhaps you need to print the contents first then increment it to point next element.



int arr[5] = 1, 2, 3, 4, 5 ;
int * ptr = arr;

for (int i = 0; i < 5; i++)
(*ptr) += 2;
printf("%d", (*ptr));
ptr++;






share|improve this answer



































    1



















    The reason for your error is the fact that you make ptr point to the next value before printing your current value(the value you actually want to be printed).
    Let's consider the first step of your for loop, line by line, and keep in mind that in the beginning you made ptr point to the first element of the array(int * ptr = arr;):



    1. (*ptr) += 2; - this line is equivalent to (*ptr) = (*ptr) + 2; which means "increase by 2 the value located in the memory address pointed by ptr", so now the first element of the array is 3 (ptr is unchanged, it points to the first element of the array).

    2. ptr++; - this line increments ptr, or in other words ptr will now point to the next memory location, in your case the second element of the array. First element is 3, the value of the second element is unchanged.

    3. printf("%d", (*ptr)); - this line prints the value stored in the memory location pointed by ptr, but you made ptr point to the next location in the previous line, so ptr is pointing, as I said before, to the second element.

    I hope you understand what happens in the next steps of your for loop.






    share|improve this answer

































      0



















      The reason it does not work is because you incremented the pointer before printing it out.



      for (int i = 0; i < 5; i++) 
      (*ptr) += 2;
      /* ptr++; */
      printf("%d", *ptr++);
      /* ^^ increment after */






      share|improve this answer

































        0



















        As people here have said, your output is wrong because you increment ptr before printing its content.



        The reason you are getting values like "-858993460" is



        ptr = arr sets ptr to the arrays memory location. The way this works is, arr has a specific memory location and reserves that memory location and all the ones following it until memorylocation+(length-1).



        So assuming arr is at location "15007140".



        Then you set the values on each memory location as following:



        15007140 = 1
        15007144 = 2
        15007148 = 3
        15007152 = 4
        15007156 = 5


        Doing ptr=arr essentially sets ptr=15007140. When calling (*ptr) you get access to the value in memory location 15007140. doing ptr++ increases 15007140 to 15007144. if you call (*ptr) you get access to the value in that location, which is 2 in this case.



        if you increase ptr further and further, you can actually increase it beyond 15007156 (which is the end of the array), thus getting access to memory addresses and their values, which are no direct part of your code (as you saw with the -858993460 in your case).



        Because ptr starts at the address of the first array position, doing ptr++; before printing, you end up printing the value of array position arr[1] first, and printing "arr[6]" last (but because your array is only of length 5, "arr[6]" is actually something unrelated to your array within your memory)



        "Correct" code would be:



        for (int i = 0; i < 5; i++) 
        (*ptr) += 2;
        printf("%drn", ptr);
        ptr++;






        share|improve this answer

































          -1



















          In the first code:
          (*ptr) += 2; It is increasing the value pointed by 'ptr' by 2 .



          ptr++; It increments the pointer by position 1, that means it points to the next element. At the end of loop it is pointing to arr[5] which has a garbage value.






          share|improve this answer





















          • 1





            has a garbage value - how do you know that? Accessing arr[5] is undefined behavior, you shouldn't make any assumptions what happens on such access.

            – Kamil Cuk
            Jul 17 at 9:34


















          -1



















          If you're already using a for loop.
          Replace ptr++ with ptr+i.



          int arr[5] = 1, 2, 3, 4, 5 ;
          int * ptr = arr;

          for (int i = 0; i < 5; i++)
          *(ptr + i) += 2;
          printf("%d", *(ptr + i));






          share|improve this answer























          • 1





            ptr+i; ? What does prt+i do? It just adds i to ptr and discards the result?

            – Kamil Cuk
            Jul 17 at 9:34












          • *(Ptr + i) = ptr[ i ]

            – sergeyrar
            Jul 17 at 9:38











          • Sorry, fixed code.

            – sergeyrar
            Jul 17 at 9:42











          • The code is still wrong and won't produce the expected output the OP was looking for

            – Spikatrix
            Jul 17 at 9:46











          • Looks so simple, and yet so complicated :D

            – sergeyrar
            Jul 17 at 10:06












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );














          draft saved

          draft discarded
















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57072416%2fdifference-in-printing-out-pointer-value-vs-array%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown


























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          9



















          int arr[5] = 1, 2, 3, 4, 5 ;
          int * ptr = arr;

          for (int i = 0; i < 5; i++)
          (*ptr) += 2;
          ptr++;
          printf("%d", (*ptr));



          The reason is you are incrementing the pointer first and then printing its content.



          Perhaps you need to print the contents first then increment it to point next element.



          int arr[5] = 1, 2, 3, 4, 5 ;
          int * ptr = arr;

          for (int i = 0; i < 5; i++)
          (*ptr) += 2;
          printf("%d", (*ptr));
          ptr++;






          share|improve this answer
































            9



















            int arr[5] = 1, 2, 3, 4, 5 ;
            int * ptr = arr;

            for (int i = 0; i < 5; i++)
            (*ptr) += 2;
            ptr++;
            printf("%d", (*ptr));



            The reason is you are incrementing the pointer first and then printing its content.



            Perhaps you need to print the contents first then increment it to point next element.



            int arr[5] = 1, 2, 3, 4, 5 ;
            int * ptr = arr;

            for (int i = 0; i < 5; i++)
            (*ptr) += 2;
            printf("%d", (*ptr));
            ptr++;






            share|improve this answer






























              9














              9










              9










              int arr[5] = 1, 2, 3, 4, 5 ;
              int * ptr = arr;

              for (int i = 0; i < 5; i++)
              (*ptr) += 2;
              ptr++;
              printf("%d", (*ptr));



              The reason is you are incrementing the pointer first and then printing its content.



              Perhaps you need to print the contents first then increment it to point next element.



              int arr[5] = 1, 2, 3, 4, 5 ;
              int * ptr = arr;

              for (int i = 0; i < 5; i++)
              (*ptr) += 2;
              printf("%d", (*ptr));
              ptr++;






              share|improve this answer
















              int arr[5] = 1, 2, 3, 4, 5 ;
              int * ptr = arr;

              for (int i = 0; i < 5; i++)
              (*ptr) += 2;
              ptr++;
              printf("%d", (*ptr));



              The reason is you are incrementing the pointer first and then printing its content.



              Perhaps you need to print the contents first then increment it to point next element.



              int arr[5] = 1, 2, 3, 4, 5 ;
              int * ptr = arr;

              for (int i = 0; i < 5; i++)
              (*ptr) += 2;
              printf("%d", (*ptr));
              ptr++;







              share|improve this answer















              share|improve this answer




              share|improve this answer








              edited Jul 17 at 9:18









              Rakete1111

              37.5k10 gold badges92 silver badges127 bronze badges




              37.5k10 gold badges92 silver badges127 bronze badges










              answered Jul 17 at 9:17









              kiran Biradarkiran Biradar

              10k3 gold badges12 silver badges32 bronze badges




              10k3 gold badges12 silver badges32 bronze badges


























                  1



















                  The reason for your error is the fact that you make ptr point to the next value before printing your current value(the value you actually want to be printed).
                  Let's consider the first step of your for loop, line by line, and keep in mind that in the beginning you made ptr point to the first element of the array(int * ptr = arr;):



                  1. (*ptr) += 2; - this line is equivalent to (*ptr) = (*ptr) + 2; which means "increase by 2 the value located in the memory address pointed by ptr", so now the first element of the array is 3 (ptr is unchanged, it points to the first element of the array).

                  2. ptr++; - this line increments ptr, or in other words ptr will now point to the next memory location, in your case the second element of the array. First element is 3, the value of the second element is unchanged.

                  3. printf("%d", (*ptr)); - this line prints the value stored in the memory location pointed by ptr, but you made ptr point to the next location in the previous line, so ptr is pointing, as I said before, to the second element.

                  I hope you understand what happens in the next steps of your for loop.






                  share|improve this answer






























                    1



















                    The reason for your error is the fact that you make ptr point to the next value before printing your current value(the value you actually want to be printed).
                    Let's consider the first step of your for loop, line by line, and keep in mind that in the beginning you made ptr point to the first element of the array(int * ptr = arr;):



                    1. (*ptr) += 2; - this line is equivalent to (*ptr) = (*ptr) + 2; which means "increase by 2 the value located in the memory address pointed by ptr", so now the first element of the array is 3 (ptr is unchanged, it points to the first element of the array).

                    2. ptr++; - this line increments ptr, or in other words ptr will now point to the next memory location, in your case the second element of the array. First element is 3, the value of the second element is unchanged.

                    3. printf("%d", (*ptr)); - this line prints the value stored in the memory location pointed by ptr, but you made ptr point to the next location in the previous line, so ptr is pointing, as I said before, to the second element.

                    I hope you understand what happens in the next steps of your for loop.






                    share|improve this answer




























                      1














                      1










                      1










                      The reason for your error is the fact that you make ptr point to the next value before printing your current value(the value you actually want to be printed).
                      Let's consider the first step of your for loop, line by line, and keep in mind that in the beginning you made ptr point to the first element of the array(int * ptr = arr;):



                      1. (*ptr) += 2; - this line is equivalent to (*ptr) = (*ptr) + 2; which means "increase by 2 the value located in the memory address pointed by ptr", so now the first element of the array is 3 (ptr is unchanged, it points to the first element of the array).

                      2. ptr++; - this line increments ptr, or in other words ptr will now point to the next memory location, in your case the second element of the array. First element is 3, the value of the second element is unchanged.

                      3. printf("%d", (*ptr)); - this line prints the value stored in the memory location pointed by ptr, but you made ptr point to the next location in the previous line, so ptr is pointing, as I said before, to the second element.

                      I hope you understand what happens in the next steps of your for loop.






                      share|improve this answer














                      The reason for your error is the fact that you make ptr point to the next value before printing your current value(the value you actually want to be printed).
                      Let's consider the first step of your for loop, line by line, and keep in mind that in the beginning you made ptr point to the first element of the array(int * ptr = arr;):



                      1. (*ptr) += 2; - this line is equivalent to (*ptr) = (*ptr) + 2; which means "increase by 2 the value located in the memory address pointed by ptr", so now the first element of the array is 3 (ptr is unchanged, it points to the first element of the array).

                      2. ptr++; - this line increments ptr, or in other words ptr will now point to the next memory location, in your case the second element of the array. First element is 3, the value of the second element is unchanged.

                      3. printf("%d", (*ptr)); - this line prints the value stored in the memory location pointed by ptr, but you made ptr point to the next location in the previous line, so ptr is pointing, as I said before, to the second element.

                      I hope you understand what happens in the next steps of your for loop.







                      share|improve this answer













                      share|improve this answer




                      share|improve this answer










                      answered Jul 17 at 9:31









                      Theodor BadeaTheodor Badea

                      3156 bronze badges




                      3156 bronze badges
























                          0



















                          The reason it does not work is because you incremented the pointer before printing it out.



                          for (int i = 0; i < 5; i++) 
                          (*ptr) += 2;
                          /* ptr++; */
                          printf("%d", *ptr++);
                          /* ^^ increment after */






                          share|improve this answer






























                            0



















                            The reason it does not work is because you incremented the pointer before printing it out.



                            for (int i = 0; i < 5; i++) 
                            (*ptr) += 2;
                            /* ptr++; */
                            printf("%d", *ptr++);
                            /* ^^ increment after */






                            share|improve this answer




























                              0














                              0










                              0










                              The reason it does not work is because you incremented the pointer before printing it out.



                              for (int i = 0; i < 5; i++) 
                              (*ptr) += 2;
                              /* ptr++; */
                              printf("%d", *ptr++);
                              /* ^^ increment after */






                              share|improve this answer














                              The reason it does not work is because you incremented the pointer before printing it out.



                              for (int i = 0; i < 5; i++) 
                              (*ptr) += 2;
                              /* ptr++; */
                              printf("%d", *ptr++);
                              /* ^^ increment after */







                              share|improve this answer













                              share|improve this answer




                              share|improve this answer










                              answered Jul 17 at 9:40









                              Andreas DMAndreas DM

                              7,5565 gold badges27 silver badges55 bronze badges




                              7,5565 gold badges27 silver badges55 bronze badges
























                                  0



















                                  As people here have said, your output is wrong because you increment ptr before printing its content.



                                  The reason you are getting values like "-858993460" is



                                  ptr = arr sets ptr to the arrays memory location. The way this works is, arr has a specific memory location and reserves that memory location and all the ones following it until memorylocation+(length-1).



                                  So assuming arr is at location "15007140".



                                  Then you set the values on each memory location as following:



                                  15007140 = 1
                                  15007144 = 2
                                  15007148 = 3
                                  15007152 = 4
                                  15007156 = 5


                                  Doing ptr=arr essentially sets ptr=15007140. When calling (*ptr) you get access to the value in memory location 15007140. doing ptr++ increases 15007140 to 15007144. if you call (*ptr) you get access to the value in that location, which is 2 in this case.



                                  if you increase ptr further and further, you can actually increase it beyond 15007156 (which is the end of the array), thus getting access to memory addresses and their values, which are no direct part of your code (as you saw with the -858993460 in your case).



                                  Because ptr starts at the address of the first array position, doing ptr++; before printing, you end up printing the value of array position arr[1] first, and printing "arr[6]" last (but because your array is only of length 5, "arr[6]" is actually something unrelated to your array within your memory)



                                  "Correct" code would be:



                                  for (int i = 0; i < 5; i++) 
                                  (*ptr) += 2;
                                  printf("%drn", ptr);
                                  ptr++;






                                  share|improve this answer






























                                    0



















                                    As people here have said, your output is wrong because you increment ptr before printing its content.



                                    The reason you are getting values like "-858993460" is



                                    ptr = arr sets ptr to the arrays memory location. The way this works is, arr has a specific memory location and reserves that memory location and all the ones following it until memorylocation+(length-1).



                                    So assuming arr is at location "15007140".



                                    Then you set the values on each memory location as following:



                                    15007140 = 1
                                    15007144 = 2
                                    15007148 = 3
                                    15007152 = 4
                                    15007156 = 5


                                    Doing ptr=arr essentially sets ptr=15007140. When calling (*ptr) you get access to the value in memory location 15007140. doing ptr++ increases 15007140 to 15007144. if you call (*ptr) you get access to the value in that location, which is 2 in this case.



                                    if you increase ptr further and further, you can actually increase it beyond 15007156 (which is the end of the array), thus getting access to memory addresses and their values, which are no direct part of your code (as you saw with the -858993460 in your case).



                                    Because ptr starts at the address of the first array position, doing ptr++; before printing, you end up printing the value of array position arr[1] first, and printing "arr[6]" last (but because your array is only of length 5, "arr[6]" is actually something unrelated to your array within your memory)



                                    "Correct" code would be:



                                    for (int i = 0; i < 5; i++) 
                                    (*ptr) += 2;
                                    printf("%drn", ptr);
                                    ptr++;






                                    share|improve this answer




























                                      0














                                      0










                                      0










                                      As people here have said, your output is wrong because you increment ptr before printing its content.



                                      The reason you are getting values like "-858993460" is



                                      ptr = arr sets ptr to the arrays memory location. The way this works is, arr has a specific memory location and reserves that memory location and all the ones following it until memorylocation+(length-1).



                                      So assuming arr is at location "15007140".



                                      Then you set the values on each memory location as following:



                                      15007140 = 1
                                      15007144 = 2
                                      15007148 = 3
                                      15007152 = 4
                                      15007156 = 5


                                      Doing ptr=arr essentially sets ptr=15007140. When calling (*ptr) you get access to the value in memory location 15007140. doing ptr++ increases 15007140 to 15007144. if you call (*ptr) you get access to the value in that location, which is 2 in this case.



                                      if you increase ptr further and further, you can actually increase it beyond 15007156 (which is the end of the array), thus getting access to memory addresses and their values, which are no direct part of your code (as you saw with the -858993460 in your case).



                                      Because ptr starts at the address of the first array position, doing ptr++; before printing, you end up printing the value of array position arr[1] first, and printing "arr[6]" last (but because your array is only of length 5, "arr[6]" is actually something unrelated to your array within your memory)



                                      "Correct" code would be:



                                      for (int i = 0; i < 5; i++) 
                                      (*ptr) += 2;
                                      printf("%drn", ptr);
                                      ptr++;






                                      share|improve this answer














                                      As people here have said, your output is wrong because you increment ptr before printing its content.



                                      The reason you are getting values like "-858993460" is



                                      ptr = arr sets ptr to the arrays memory location. The way this works is, arr has a specific memory location and reserves that memory location and all the ones following it until memorylocation+(length-1).



                                      So assuming arr is at location "15007140".



                                      Then you set the values on each memory location as following:



                                      15007140 = 1
                                      15007144 = 2
                                      15007148 = 3
                                      15007152 = 4
                                      15007156 = 5


                                      Doing ptr=arr essentially sets ptr=15007140. When calling (*ptr) you get access to the value in memory location 15007140. doing ptr++ increases 15007140 to 15007144. if you call (*ptr) you get access to the value in that location, which is 2 in this case.



                                      if you increase ptr further and further, you can actually increase it beyond 15007156 (which is the end of the array), thus getting access to memory addresses and their values, which are no direct part of your code (as you saw with the -858993460 in your case).



                                      Because ptr starts at the address of the first array position, doing ptr++; before printing, you end up printing the value of array position arr[1] first, and printing "arr[6]" last (but because your array is only of length 5, "arr[6]" is actually something unrelated to your array within your memory)



                                      "Correct" code would be:



                                      for (int i = 0; i < 5; i++) 
                                      (*ptr) += 2;
                                      printf("%drn", ptr);
                                      ptr++;







                                      share|improve this answer













                                      share|improve this answer




                                      share|improve this answer










                                      answered Jul 17 at 10:27









                                      AlanAlan

                                      5641 silver badge19 bronze badges




                                      5641 silver badge19 bronze badges
























                                          -1



















                                          In the first code:
                                          (*ptr) += 2; It is increasing the value pointed by 'ptr' by 2 .



                                          ptr++; It increments the pointer by position 1, that means it points to the next element. At the end of loop it is pointing to arr[5] which has a garbage value.






                                          share|improve this answer





















                                          • 1





                                            has a garbage value - how do you know that? Accessing arr[5] is undefined behavior, you shouldn't make any assumptions what happens on such access.

                                            – Kamil Cuk
                                            Jul 17 at 9:34















                                          -1



















                                          In the first code:
                                          (*ptr) += 2; It is increasing the value pointed by 'ptr' by 2 .



                                          ptr++; It increments the pointer by position 1, that means it points to the next element. At the end of loop it is pointing to arr[5] which has a garbage value.






                                          share|improve this answer





















                                          • 1





                                            has a garbage value - how do you know that? Accessing arr[5] is undefined behavior, you shouldn't make any assumptions what happens on such access.

                                            – Kamil Cuk
                                            Jul 17 at 9:34













                                          -1














                                          -1










                                          -1










                                          In the first code:
                                          (*ptr) += 2; It is increasing the value pointed by 'ptr' by 2 .



                                          ptr++; It increments the pointer by position 1, that means it points to the next element. At the end of loop it is pointing to arr[5] which has a garbage value.






                                          share|improve this answer














                                          In the first code:
                                          (*ptr) += 2; It is increasing the value pointed by 'ptr' by 2 .



                                          ptr++; It increments the pointer by position 1, that means it points to the next element. At the end of loop it is pointing to arr[5] which has a garbage value.







                                          share|improve this answer













                                          share|improve this answer




                                          share|improve this answer










                                          answered Jul 17 at 9:24









                                          Ankush PanditAnkush Pandit

                                          147 bronze badges




                                          147 bronze badges










                                          • 1





                                            has a garbage value - how do you know that? Accessing arr[5] is undefined behavior, you shouldn't make any assumptions what happens on such access.

                                            – Kamil Cuk
                                            Jul 17 at 9:34












                                          • 1





                                            has a garbage value - how do you know that? Accessing arr[5] is undefined behavior, you shouldn't make any assumptions what happens on such access.

                                            – Kamil Cuk
                                            Jul 17 at 9:34







                                          1




                                          1





                                          has a garbage value - how do you know that? Accessing arr[5] is undefined behavior, you shouldn't make any assumptions what happens on such access.

                                          – Kamil Cuk
                                          Jul 17 at 9:34





                                          has a garbage value - how do you know that? Accessing arr[5] is undefined behavior, you shouldn't make any assumptions what happens on such access.

                                          – Kamil Cuk
                                          Jul 17 at 9:34











                                          -1



















                                          If you're already using a for loop.
                                          Replace ptr++ with ptr+i.



                                          int arr[5] = 1, 2, 3, 4, 5 ;
                                          int * ptr = arr;

                                          for (int i = 0; i < 5; i++)
                                          *(ptr + i) += 2;
                                          printf("%d", *(ptr + i));






                                          share|improve this answer























                                          • 1





                                            ptr+i; ? What does prt+i do? It just adds i to ptr and discards the result?

                                            – Kamil Cuk
                                            Jul 17 at 9:34












                                          • *(Ptr + i) = ptr[ i ]

                                            – sergeyrar
                                            Jul 17 at 9:38











                                          • Sorry, fixed code.

                                            – sergeyrar
                                            Jul 17 at 9:42











                                          • The code is still wrong and won't produce the expected output the OP was looking for

                                            – Spikatrix
                                            Jul 17 at 9:46











                                          • Looks so simple, and yet so complicated :D

                                            – sergeyrar
                                            Jul 17 at 10:06















                                          -1



















                                          If you're already using a for loop.
                                          Replace ptr++ with ptr+i.



                                          int arr[5] = 1, 2, 3, 4, 5 ;
                                          int * ptr = arr;

                                          for (int i = 0; i < 5; i++)
                                          *(ptr + i) += 2;
                                          printf("%d", *(ptr + i));






                                          share|improve this answer























                                          • 1





                                            ptr+i; ? What does prt+i do? It just adds i to ptr and discards the result?

                                            – Kamil Cuk
                                            Jul 17 at 9:34












                                          • *(Ptr + i) = ptr[ i ]

                                            – sergeyrar
                                            Jul 17 at 9:38











                                          • Sorry, fixed code.

                                            – sergeyrar
                                            Jul 17 at 9:42











                                          • The code is still wrong and won't produce the expected output the OP was looking for

                                            – Spikatrix
                                            Jul 17 at 9:46











                                          • Looks so simple, and yet so complicated :D

                                            – sergeyrar
                                            Jul 17 at 10:06













                                          -1














                                          -1










                                          -1










                                          If you're already using a for loop.
                                          Replace ptr++ with ptr+i.



                                          int arr[5] = 1, 2, 3, 4, 5 ;
                                          int * ptr = arr;

                                          for (int i = 0; i < 5; i++)
                                          *(ptr + i) += 2;
                                          printf("%d", *(ptr + i));






                                          share|improve this answer
















                                          If you're already using a for loop.
                                          Replace ptr++ with ptr+i.



                                          int arr[5] = 1, 2, 3, 4, 5 ;
                                          int * ptr = arr;

                                          for (int i = 0; i < 5; i++)
                                          *(ptr + i) += 2;
                                          printf("%d", *(ptr + i));







                                          share|improve this answer















                                          share|improve this answer




                                          share|improve this answer








                                          edited Jul 17 at 10:05

























                                          answered Jul 17 at 9:32









                                          sergeyrarsergeyrar

                                          2943 silver badges12 bronze badges




                                          2943 silver badges12 bronze badges










                                          • 1





                                            ptr+i; ? What does prt+i do? It just adds i to ptr and discards the result?

                                            – Kamil Cuk
                                            Jul 17 at 9:34












                                          • *(Ptr + i) = ptr[ i ]

                                            – sergeyrar
                                            Jul 17 at 9:38











                                          • Sorry, fixed code.

                                            – sergeyrar
                                            Jul 17 at 9:42











                                          • The code is still wrong and won't produce the expected output the OP was looking for

                                            – Spikatrix
                                            Jul 17 at 9:46











                                          • Looks so simple, and yet so complicated :D

                                            – sergeyrar
                                            Jul 17 at 10:06












                                          • 1





                                            ptr+i; ? What does prt+i do? It just adds i to ptr and discards the result?

                                            – Kamil Cuk
                                            Jul 17 at 9:34












                                          • *(Ptr + i) = ptr[ i ]

                                            – sergeyrar
                                            Jul 17 at 9:38











                                          • Sorry, fixed code.

                                            – sergeyrar
                                            Jul 17 at 9:42











                                          • The code is still wrong and won't produce the expected output the OP was looking for

                                            – Spikatrix
                                            Jul 17 at 9:46











                                          • Looks so simple, and yet so complicated :D

                                            – sergeyrar
                                            Jul 17 at 10:06







                                          1




                                          1





                                          ptr+i; ? What does prt+i do? It just adds i to ptr and discards the result?

                                          – Kamil Cuk
                                          Jul 17 at 9:34






                                          ptr+i; ? What does prt+i do? It just adds i to ptr and discards the result?

                                          – Kamil Cuk
                                          Jul 17 at 9:34














                                          *(Ptr + i) = ptr[ i ]

                                          – sergeyrar
                                          Jul 17 at 9:38





                                          *(Ptr + i) = ptr[ i ]

                                          – sergeyrar
                                          Jul 17 at 9:38













                                          Sorry, fixed code.

                                          – sergeyrar
                                          Jul 17 at 9:42





                                          Sorry, fixed code.

                                          – sergeyrar
                                          Jul 17 at 9:42













                                          The code is still wrong and won't produce the expected output the OP was looking for

                                          – Spikatrix
                                          Jul 17 at 9:46





                                          The code is still wrong and won't produce the expected output the OP was looking for

                                          – Spikatrix
                                          Jul 17 at 9:46













                                          Looks so simple, and yet so complicated :D

                                          – sergeyrar
                                          Jul 17 at 10:06





                                          Looks so simple, and yet so complicated :D

                                          – sergeyrar
                                          Jul 17 at 10:06


















                                          draft saved

                                          draft discarded















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57072416%2fdifference-in-printing-out-pointer-value-vs-array%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown









                                          Popular posts from this blog

                                          Tamil (spriik) Luke uk diar | Nawigatjuun

                                          Align equal signs while including text over equalitiesAMS align: left aligned text/math plus multicolumn alignmentMultiple alignmentsAligning equations in multiple placesNumbering and aligning an equation with multiple columnsHow to align one equation with another multline equationUsing \ in environments inside the begintabularxNumber equations and preserving alignment of equal signsHow can I align equations to the left and to the right?Double equation alignment problem within align enviromentAligned within align: Why are they right-aligned?

                                          Where does the image of a data connector as a sharp metal spike originate from?Where does the concept of infected people turning into zombies only after death originate from?Where does the motif of a reanimated human head originate?Where did the notion that Dragons could speak originate?Where does the archetypal image of the 'Grey' alien come from?Where did the suffix '-Man' originate?Where does the notion of being injured or killed by an illusion originate?Where did the term “sophont” originate?Where does the trope of magic spells being driven by advanced technology originate from?Where did the term “the living impaired” originate?