Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the code attached below isn't working?

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

 int main(void)
 {
    int a=10 ;
    int *p;
    p = &a;
    *(p+1) = 20;
    printf("The value at (p+1) is %d\n",*(p+1));

    return 0;
  }

I’m trying to do some pointer arithmetic and trying to implement the code. I’m trying to assign value 20 to next address in the memory using *(p+1) and print it using the printf statement, but my code isn’t producing any output. Why is it so?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Look at it this way, *(p + 1) is the same as having p[1] this means you are looking for the data in a[1] but a is not an array, a[1] does not exist in your program, we don’t really know what’s in the memory location you are trying to access, that is why your program suffers from undefined behavior.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading