can you explain me why it is possible p[-1]?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















int *p[10]={5,663,36,6};

*(p - 1) = 'e';

int c=*(p-1);

printf("%c",c);


i am not able to understand why we use negative number in array index



*(p - 1) = 'e';









share|improve this question




















  • 5





    You can't, really. It's undefined behavior, so there's no telling what happens. It might work as intended, but it might just as well crash the program or do something even worse. In practice what most likely happens is that it calculates the memory address and just writes/reads to/from it anyway, which may cause data corrupion (because it's overwriting something else), stack corruption (by writing over the stack pointer), or make the OS detect an illegal memory access and crash the program.

    – Blaze
    Nov 23 '18 at 15:15













  • Also, you can't assign an integer value to a pointer without a cast.

    – EOF
    Nov 23 '18 at 15:17


















0















int *p[10]={5,663,36,6};

*(p - 1) = 'e';

int c=*(p-1);

printf("%c",c);


i am not able to understand why we use negative number in array index



*(p - 1) = 'e';









share|improve this question




















  • 5





    You can't, really. It's undefined behavior, so there's no telling what happens. It might work as intended, but it might just as well crash the program or do something even worse. In practice what most likely happens is that it calculates the memory address and just writes/reads to/from it anyway, which may cause data corrupion (because it's overwriting something else), stack corruption (by writing over the stack pointer), or make the OS detect an illegal memory access and crash the program.

    – Blaze
    Nov 23 '18 at 15:15













  • Also, you can't assign an integer value to a pointer without a cast.

    – EOF
    Nov 23 '18 at 15:17














0












0








0








int *p[10]={5,663,36,6};

*(p - 1) = 'e';

int c=*(p-1);

printf("%c",c);


i am not able to understand why we use negative number in array index



*(p - 1) = 'e';









share|improve this question
















int *p[10]={5,663,36,6};

*(p - 1) = 'e';

int c=*(p-1);

printf("%c",c);


i am not able to understand why we use negative number in array index



*(p - 1) = 'e';






c






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 15:21









Blaze

7,5241832




7,5241832










asked Nov 23 '18 at 15:13









Learning cLearning c

6




6








  • 5





    You can't, really. It's undefined behavior, so there's no telling what happens. It might work as intended, but it might just as well crash the program or do something even worse. In practice what most likely happens is that it calculates the memory address and just writes/reads to/from it anyway, which may cause data corrupion (because it's overwriting something else), stack corruption (by writing over the stack pointer), or make the OS detect an illegal memory access and crash the program.

    – Blaze
    Nov 23 '18 at 15:15













  • Also, you can't assign an integer value to a pointer without a cast.

    – EOF
    Nov 23 '18 at 15:17














  • 5





    You can't, really. It's undefined behavior, so there's no telling what happens. It might work as intended, but it might just as well crash the program or do something even worse. In practice what most likely happens is that it calculates the memory address and just writes/reads to/from it anyway, which may cause data corrupion (because it's overwriting something else), stack corruption (by writing over the stack pointer), or make the OS detect an illegal memory access and crash the program.

    – Blaze
    Nov 23 '18 at 15:15













  • Also, you can't assign an integer value to a pointer without a cast.

    – EOF
    Nov 23 '18 at 15:17








5




5





You can't, really. It's undefined behavior, so there's no telling what happens. It might work as intended, but it might just as well crash the program or do something even worse. In practice what most likely happens is that it calculates the memory address and just writes/reads to/from it anyway, which may cause data corrupion (because it's overwriting something else), stack corruption (by writing over the stack pointer), or make the OS detect an illegal memory access and crash the program.

– Blaze
Nov 23 '18 at 15:15







You can't, really. It's undefined behavior, so there's no telling what happens. It might work as intended, but it might just as well crash the program or do something even worse. In practice what most likely happens is that it calculates the memory address and just writes/reads to/from it anyway, which may cause data corrupion (because it's overwriting something else), stack corruption (by writing over the stack pointer), or make the OS detect an illegal memory access and crash the program.

– Blaze
Nov 23 '18 at 15:15















Also, you can't assign an integer value to a pointer without a cast.

– EOF
Nov 23 '18 at 15:17





Also, you can't assign an integer value to a pointer without a cast.

– EOF
Nov 23 '18 at 15:17












3 Answers
3






active

oldest

votes


















3














For your example it would be undefined behaviour, but there are situations where you might want to use it, notably if your pointer was pointing to somewhere inside an array and you check that you are still inside the bounds of the array.



Like in this example...



#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv){
char hello="worlld";
char *p;

for(p=hello;*p!='';p++) {
if ((p>hello) && (p[-1]==p[0])) {
printf("%cn",p[0]);
}
}
return(0);
}





share|improve this answer































    2














    The language does not prevent you from using negative numbers in indexing of an array or a pointer. This does not meant that it is always correct. i.e. in your example it would access an array element which is 1 position before the beginning of the array. in other words you access invalid memory addres.



    However in the situation like the following, where p1 points to a non-0 element of the array, you can use negative indexes:



    int p = {1,2,3,4};
    int *p1 = &p[1];

    int x = *(p1-1);
    int y = p1[-1]; // equivalent to the previous one


    In both cases 'x' and 'y' will become '1';






    share|improve this answer































      0















      i am not able to understand why we use negative number in array index




      That's because




      1. you apparently think is an array operator, but it is not. It is a pointer operator, defined in terms of pointer arithmetic, which, in a general sense, permits subtracting integers from pointers.


      2. you seem to have an expectation of some particular kind of behavior arising from evaluating your example code, but it exhibits undefined behavior on account of performing arithmetic on pointer p that does not produce a result pointing into (or just past the end of) the same object that p points [in]to. "Undefined" means exactly what it says. Although an obvious program failure or error message might be emitted, you cannot rely on that, or on any other particular behavior. Of the entire program.







      share|improve this answer



















      • 2





        Most noticeably one can also write -1[x] reversing the 'array' and 'index' because the standard says a[b] is just *(a+b) and + is commutative.

        – Goswin von Brederlow
        Nov 23 '18 at 16:13












      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/3.0/"u003ecc by-sa 3.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%2f53449118%2fcan-you-explain-me-why-it-is-possible-p-1%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      For your example it would be undefined behaviour, but there are situations where you might want to use it, notably if your pointer was pointing to somewhere inside an array and you check that you are still inside the bounds of the array.



      Like in this example...



      #include <stdio.h>
      #include <stdlib.h>

      int main(int argc, char *argv){
      char hello="worlld";
      char *p;

      for(p=hello;*p!='';p++) {
      if ((p>hello) && (p[-1]==p[0])) {
      printf("%cn",p[0]);
      }
      }
      return(0);
      }





      share|improve this answer




























        3














        For your example it would be undefined behaviour, but there are situations where you might want to use it, notably if your pointer was pointing to somewhere inside an array and you check that you are still inside the bounds of the array.



        Like in this example...



        #include <stdio.h>
        #include <stdlib.h>

        int main(int argc, char *argv){
        char hello="worlld";
        char *p;

        for(p=hello;*p!='';p++) {
        if ((p>hello) && (p[-1]==p[0])) {
        printf("%cn",p[0]);
        }
        }
        return(0);
        }





        share|improve this answer


























          3












          3








          3







          For your example it would be undefined behaviour, but there are situations where you might want to use it, notably if your pointer was pointing to somewhere inside an array and you check that you are still inside the bounds of the array.



          Like in this example...



          #include <stdio.h>
          #include <stdlib.h>

          int main(int argc, char *argv){
          char hello="worlld";
          char *p;

          for(p=hello;*p!='';p++) {
          if ((p>hello) && (p[-1]==p[0])) {
          printf("%cn",p[0]);
          }
          }
          return(0);
          }





          share|improve this answer













          For your example it would be undefined behaviour, but there are situations where you might want to use it, notably if your pointer was pointing to somewhere inside an array and you check that you are still inside the bounds of the array.



          Like in this example...



          #include <stdio.h>
          #include <stdlib.h>

          int main(int argc, char *argv){
          char hello="worlld";
          char *p;

          for(p=hello;*p!='';p++) {
          if ((p>hello) && (p[-1]==p[0])) {
          printf("%cn",p[0]);
          }
          }
          return(0);
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 15:24









          Chris TurnerChris Turner

          7,31011118




          7,31011118

























              2














              The language does not prevent you from using negative numbers in indexing of an array or a pointer. This does not meant that it is always correct. i.e. in your example it would access an array element which is 1 position before the beginning of the array. in other words you access invalid memory addres.



              However in the situation like the following, where p1 points to a non-0 element of the array, you can use negative indexes:



              int p = {1,2,3,4};
              int *p1 = &p[1];

              int x = *(p1-1);
              int y = p1[-1]; // equivalent to the previous one


              In both cases 'x' and 'y' will become '1';






              share|improve this answer




























                2














                The language does not prevent you from using negative numbers in indexing of an array or a pointer. This does not meant that it is always correct. i.e. in your example it would access an array element which is 1 position before the beginning of the array. in other words you access invalid memory addres.



                However in the situation like the following, where p1 points to a non-0 element of the array, you can use negative indexes:



                int p = {1,2,3,4};
                int *p1 = &p[1];

                int x = *(p1-1);
                int y = p1[-1]; // equivalent to the previous one


                In both cases 'x' and 'y' will become '1';






                share|improve this answer


























                  2












                  2








                  2







                  The language does not prevent you from using negative numbers in indexing of an array or a pointer. This does not meant that it is always correct. i.e. in your example it would access an array element which is 1 position before the beginning of the array. in other words you access invalid memory addres.



                  However in the situation like the following, where p1 points to a non-0 element of the array, you can use negative indexes:



                  int p = {1,2,3,4};
                  int *p1 = &p[1];

                  int x = *(p1-1);
                  int y = p1[-1]; // equivalent to the previous one


                  In both cases 'x' and 'y' will become '1';






                  share|improve this answer













                  The language does not prevent you from using negative numbers in indexing of an array or a pointer. This does not meant that it is always correct. i.e. in your example it would access an array element which is 1 position before the beginning of the array. in other words you access invalid memory addres.



                  However in the situation like the following, where p1 points to a non-0 element of the array, you can use negative indexes:



                  int p = {1,2,3,4};
                  int *p1 = &p[1];

                  int x = *(p1-1);
                  int y = p1[-1]; // equivalent to the previous one


                  In both cases 'x' and 'y' will become '1';







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 15:28









                  SergeSerge

                  4,13721016




                  4,13721016























                      0















                      i am not able to understand why we use negative number in array index




                      That's because




                      1. you apparently think is an array operator, but it is not. It is a pointer operator, defined in terms of pointer arithmetic, which, in a general sense, permits subtracting integers from pointers.


                      2. you seem to have an expectation of some particular kind of behavior arising from evaluating your example code, but it exhibits undefined behavior on account of performing arithmetic on pointer p that does not produce a result pointing into (or just past the end of) the same object that p points [in]to. "Undefined" means exactly what it says. Although an obvious program failure or error message might be emitted, you cannot rely on that, or on any other particular behavior. Of the entire program.







                      share|improve this answer



















                      • 2





                        Most noticeably one can also write -1[x] reversing the 'array' and 'index' because the standard says a[b] is just *(a+b) and + is commutative.

                        – Goswin von Brederlow
                        Nov 23 '18 at 16:13
















                      0















                      i am not able to understand why we use negative number in array index




                      That's because




                      1. you apparently think is an array operator, but it is not. It is a pointer operator, defined in terms of pointer arithmetic, which, in a general sense, permits subtracting integers from pointers.


                      2. you seem to have an expectation of some particular kind of behavior arising from evaluating your example code, but it exhibits undefined behavior on account of performing arithmetic on pointer p that does not produce a result pointing into (or just past the end of) the same object that p points [in]to. "Undefined" means exactly what it says. Although an obvious program failure or error message might be emitted, you cannot rely on that, or on any other particular behavior. Of the entire program.







                      share|improve this answer



















                      • 2





                        Most noticeably one can also write -1[x] reversing the 'array' and 'index' because the standard says a[b] is just *(a+b) and + is commutative.

                        – Goswin von Brederlow
                        Nov 23 '18 at 16:13














                      0












                      0








                      0








                      i am not able to understand why we use negative number in array index




                      That's because




                      1. you apparently think is an array operator, but it is not. It is a pointer operator, defined in terms of pointer arithmetic, which, in a general sense, permits subtracting integers from pointers.


                      2. you seem to have an expectation of some particular kind of behavior arising from evaluating your example code, but it exhibits undefined behavior on account of performing arithmetic on pointer p that does not produce a result pointing into (or just past the end of) the same object that p points [in]to. "Undefined" means exactly what it says. Although an obvious program failure or error message might be emitted, you cannot rely on that, or on any other particular behavior. Of the entire program.







                      share|improve this answer














                      i am not able to understand why we use negative number in array index




                      That's because




                      1. you apparently think is an array operator, but it is not. It is a pointer operator, defined in terms of pointer arithmetic, which, in a general sense, permits subtracting integers from pointers.


                      2. you seem to have an expectation of some particular kind of behavior arising from evaluating your example code, but it exhibits undefined behavior on account of performing arithmetic on pointer p that does not produce a result pointing into (or just past the end of) the same object that p points [in]to. "Undefined" means exactly what it says. Although an obvious program failure or error message might be emitted, you cannot rely on that, or on any other particular behavior. Of the entire program.








                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 23 '18 at 15:32









                      John BollingerJohn Bollinger

                      85.1k74279




                      85.1k74279








                      • 2





                        Most noticeably one can also write -1[x] reversing the 'array' and 'index' because the standard says a[b] is just *(a+b) and + is commutative.

                        – Goswin von Brederlow
                        Nov 23 '18 at 16:13














                      • 2





                        Most noticeably one can also write -1[x] reversing the 'array' and 'index' because the standard says a[b] is just *(a+b) and + is commutative.

                        – Goswin von Brederlow
                        Nov 23 '18 at 16:13








                      2




                      2





                      Most noticeably one can also write -1[x] reversing the 'array' and 'index' because the standard says a[b] is just *(a+b) and + is commutative.

                      – Goswin von Brederlow
                      Nov 23 '18 at 16:13





                      Most noticeably one can also write -1[x] reversing the 'array' and 'index' because the standard says a[b] is just *(a+b) and + is commutative.

                      – Goswin von Brederlow
                      Nov 23 '18 at 16:13


















                      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%2f53449118%2fcan-you-explain-me-why-it-is-possible-p-1%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







                      這個網誌中的熱門文章

                      Xamarin.form Move up view when keyboard appear

                      Post-Redirect-Get with Spring WebFlux and Thymeleaf

                      Anylogic : not able to use stopDelay()