Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Why is that for a pointer *p, p[0] is the address stored at p and p[1] is the address of p itself?

The code

int n = 25;  
int *p = &n;  
printf("%x\n %d\n %x\n", p, p[0], p[1]);

returns:

\<adress-of-p  
25  
\<adress-of-p>  

Of course I would never do this but in K&R states that

"if pa is a pointer, expressions may use it with a subscript; pa[i] is identical to *(pa+i).

so I was curious.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

This statement

printf("%x\n %d\n %x\n", p, p[0], p[1]);

invokes undefined behavior by two reasons.

The first one is that to output a pointer you should use a correct conversion specifier. The second one is that you may not dereference a pointer like this p[1] that does not point to a valid object.

Instead you could write for example

printf("%p\n %d\n %p\n", ( void * )p, p[0], ( void * )( p + 1 ) );
over 4 years ago · Santiago Trujillo Report

0

When you evaluate p[1] in your code, you are invoking undefined behavior so your program can do anything.

It is undefined behavior because p points at n which is just a single integer, not an array of integers. So p[0] is n, but p[1] is undefined. Basically this is an array overflow bug.

over 4 years ago · Santiago Trujillo Report

0

Your program has undefined behaviour, because it dereferences a pointer that doesn't point to anything.

The particular symptoms you have experienced are consistent with reading the next variable in the function

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!