Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does following program work pointer manipulation [duplicate]

Tags:

c

string

pointers

Possible Duplicate:
A c program from GATE paper

Here is a program which is working

#include<stdio.h>
int main ()
{
char c[]="GATE2011";
char *p=c;
printf("%s",p+p[3]-p[1]);
}

The output is

2011

Now comes the problem I am not able to understand the operation p+p[3]-p[1] what is that pointing to?

My understanding is when I declare some thing like

char c[]="GATE2011"

Then c is a pointer pointing to a string constant and the string begins with G. In next line *p=c; the pointer p is pointing to same address which c is pointing. So how does the above arithmetic work?

like image 426
Registered User Avatar asked Dec 10 '22 08:12

Registered User


2 Answers

p[3] is 'E', p[1] is 'A'. The difference between the ASCII codes A and E is 4, so p+p[3]-p[1] is equivalent to p+4, which in turn is equivalent to &p[4], and so points to the '2' character in the char array.

Anyone found writing this sort of thing in production code would be shot, though.

like image 171
Roddy Avatar answered Mar 22 '23 22:03

Roddy


It's pretty horrid code. (p+p[3]-p[1]) is simply adding and subtracting offsets to p. p[3] is (char)'E', which is 69 in ASCII. p[1] is (char)'A', which is 65 in ASCII. So the code is equivalent to:

(p+69-65)

which is:

(p+4)

So it's simply offseting the pointer by 4 elements, before passing it to printf.

Technically, this is undefined behaviour. The first part of that expression (p+69) offsets the pointer beyond the end of the array, which is not allowed by the C standard.

like image 29
Oliver Charlesworth Avatar answered Mar 23 '23 00:03

Oliver Charlesworth