473,799 Members | 2,954 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointers in C

Hi,

I came across a program as follows
main()
{
int x, y ;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1-p2);
}

The output of the above program is 1.
Can some one explain me how it is 1.
Thanks in advance.

Feb 21 '07
66 2726
Richard Heathfield wrote:
rafalp said:
>Richard Heathfield wrote:
>>rafalp said:

Well, if you change the last line to

printf("%d\n ", (char*)p1-(char*)p2);

you will get 4, ie sizeof(int), instead of 1.
No, the behaviour will still be undefined, for two separate reasons.
You're right. I should have written "you will get value >=
sizeof(int)" instead.

No, you should have written something like "the value you get, if any,
is not defined by the rules of C - to get a well-defined result, write
a well-defined program".
You are perfectly right here. I forgot about p1 < p2 case ;).
But again, the question was not "what value should I get" but "why I get
1 instead of some other value".
Feb 21 '07 #21
rafalp wrote:
santosh wrote:
rafalp wrote:
Praveen wrote:
I came across a program as follows
main()
{
int x, y ;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1-p2);
}

The output of the above program is 1.
Can some one explain me how it is 1.

Well, if you change the last line to

printf("%d\n", (char*)p1-(char*)p2);

you will get 4, ie sizeof(int), instead of 1. Is that what you expected?
The only thing you and the OP should expect is undefined behaviour.
You're both having the assumption that x and y are placed adjacently
in memory: something that's not required by the C standard.

We should expect that pointer difference between two distinct objects of
the same type is greater or equal than size of that object type.
This is exactly what you should *not* expect. If these objects are
part of an array, then the pointer difference, (in terms of
magnitude), between any two objects of this array will be a multiple
of the size of a single object. But this only holds for objects that
are a part of an array, including those returned by malloc and co.
This is not the case in the example presented by the OP.
And
that is what the question was about. The question, put it in other
words, might be: "the program outputs 1 and sizeof(int) == 4 (in this
case), so does it mean that x and y overlap in memory?". I think that it
is common among beginners to assume that pointer arithmetic works just
like int arithmetic.
Except for members of an union, objects cannot overlap in memory.

Feb 21 '07 #22
rafalp wrote:
Richard Heathfield wrote:
rafalp said:
Richard Heathfield wrote:
rafalp said:

Well, if you change the last line to

printf("%d\n" , (char*)p1-(char*)p2);

you will get 4, ie sizeof(int), instead of 1.

No, the behaviour will still be undefined, for two separate reasons.

You're right. I should have written "you will get value >=
sizeof(int)" instead.
No, you should have written something like "the value you get, if any,
is not defined by the rules of C - to get a well-defined result, write
a well-defined program".

You are perfectly right here. I forgot about p1 < p2 case ;).
But again, the question was not "what value should I get" but "why I get
1 instead of some other value".
You still don't seem to understand. It doesn't matter what the values
of p1 and p2 are. In C, objects which are not part of an array are not
guaranteed to be physically adjacent in memory. In practise it might
commonly happen to be so, but that's only because of the choices the
implementation makes and relying on it is dangerous.

So in the example presented by the OP, the value of p1-p2 could as
easily be 711935 instead of 1.

Feb 21 '07 #23
rafalp wrote:
Richard Heathfield wrote:
>rafalp said:
>>Richard Heathfield wrote:
rafalp said:

Well, if you change the last line to
>
printf("%d\ n", (char*)p1-(char*)p2);
>
you will get 4, ie sizeof(int), instead of 1.
No, the behaviour will still be undefined, for two separate reasons.
You're right. I should have written "you will get value >=
sizeof(int) " instead.

No, you should have written something like "the value you get, if any,
is not defined by the rules of C - to get a well-defined result, write
a well-defined program".

You are perfectly right here. I forgot about p1 < p2 case ;).
But again, the question was not "what value should I get" but "why I get
1 instead of some other value".
Still not quite there. *Any* value or *no value at all* is a correct
result of subtracting those two pointers.

--
Clark S. Cox III
cl*******@gmail .com
Feb 21 '07 #24
santosh said:

<snip>
does CHAR_BIT include padding bits?
Since unsigned char may not contain padding bits (see 6.2.6.2), the
answer is no.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 21 '07 #25
rafalp said:

<snip>
But again, the question was not "what value should I get" but "why I
get 1 instead of some other value".
The only reasonable answer from a standard C perspective is "because, on
this occasion, that's the value you got".

When you break the rules of C, the compiler is released from any
obligation to be predictable.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 21 '07 #26
Richard Tobin wrote, On 21/02/07 14:22:
In article <Po************ *************** ***@bt.com>,
Richard Heathfield <rj*@see.sig.in validwrote:
>>If the system the OP is using has a flat address space, and uses those
addresses for C pointers, and performs subtraction of pointers to
distinct objects as if they were in the same object, then he will get
sizeof(int) .
>The C Standard doesn't guarantee this, and no implementation is under
any obligation to provide that behaviour (even setting aside the fact
that there's no prototype in scope for printf and thus the behaviour is
undefined for another reason). Nothing in the rules says that x and y
have to be placed adjacently to each other in memory.

Quite so, but we know that they are adjacent on the OP's system (given
the assumptions I listed). Of course, it's possible that adding the
casts to char * may change that, but I doubt it.
Even given that they are adjacent and the implementation happens to
produce something that looks sensible there is no guarantee that the
answer will be positive. For example:

markg@brenda:~$ cat t.c
#include <stdio.h>

int main(void)
{
int x, y ;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", (int)(p1-p2));
return 0;
}
markg@brenda:~$ gcc -ansi -pedantic -Wall -W -O t.c
markg@brenda:~$ ./a.out
1
markg@brenda:~$ ssh hal02
markg@hal02's password:
Last unsuccessful login: Mon 19 Feb 00:06:42 2007 on ssh from
staff-vpn20.staff-vpn.causeway.co m
Last login: Wed 21 Feb 18:23:26 2007 on /dev/pts/4 from
staff-vpn21.staff-vpn.causeway.co m
*************** *************** *************** *************** *************** ****
*
*
*
*
* Welcome to AIX Version 5.3!
*
*
*
*
*
* Please see the README file in /usr/lpp/bos for information pertinent
to *
* this release of the AIX Operating System.
*
*
*
*
*
*************** *************** *************** *************** *************** ****
markg@hal02 ~ $ cat t.c
#include <stdio.h>

int main(void)
{
int x, y ;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", (int)(p1-p2));
return 0;
}
markg@hal02 ~ $ gcc -ansi -pedantic -Wall -W -O t.c
markg@hal02 ~ $ ./a.out
-1
markg@hal02 ~ $

So we have the program (with the undefined behaviour fixed) giving 1 on
one system and -1 on another with both using gcc!
For years, the unix crypt program relied on two arrays being contiguous.
A case of unwarranted chumminess with the compiler, which worked until
someone used a different compiler.
That, indeed, is bad. However, you should probably specify which unix,
since not all versions are the same ;-)
--
Flash Gordon
Feb 21 '07 #27
ri*****@cogsci. ed.ac.uk (Richard Tobin) writes:
In article <Po************ *************** ***@bt.com>,
Richard Heathfield <rj*@see.sig.in validwrote:
>>If the system the OP is using has a flat address space, and uses those
addresses for C pointers, and performs subtraction of pointers to
distinct objects as if they were in the same object, then he will get
sizeof(int) .
>>The C Standard doesn't guarantee this, and no implementation is under
any obligation to provide that behaviour (even setting aside the fact
that there's no prototype in scope for printf and thus the behaviour is
undefined for another reason). Nothing in the rules says that x and y
have to be placed adjacently to each other in memory.

Quite so, but we know that they are adjacent on the OP's system (given
the assumptions I listed). Of course, it's possible that adding the
casts to char * may change that, but I doubt it.
[...]

The assumptions you listed are not sufficient to guarantee that the
objects are adjacent. It's likely that they are, but even then
there's no reason to assume that the result of the pointer subtraction
will be positive rather than negative.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 21 '07 #28
In article <an************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
>Quite so, but we know that they are adjacent on the OP's system (given
the assumptions I listed). Of course, it's possible that adding the
casts to char * may change that, but I doubt it.
>Even given that they are adjacent and the implementation happens to
produce something that looks sensible there is no guarantee that the
answer will be positive.
We know that, without the casts to char *, the answer is 1. So if the
layout remains the same (as is likely), the answer with casts will be
sizeof(int) rather than -sizeof(int).

Though there are other loopholes. On a machine with no alignment
constraints, it's conceivable that the spacing is not a multiple of
sizeof(int), so it might be some value between sizeof(int) and twice
that.
>For years, the unix crypt program relied on two arrays being contiguous.
A case of unwarranted chumminess with the compiler, which worked until
someone used a different compiler.

That, indeed, is bad. However, you should probably specify which unix,
since not all versions are the same ;-)
I don't recall which version I found it in, probably BSD, around 1990.

I've just looked at the seventh edition code at
http://minnie.tuhs.org/UnixTree/V7/u...n/crypt.c.html
and it's in there:

/*
* The current block, divided into 2 halves.
*/
static char L[32], R[32];
[...]
encrypt(block, edflag)
char *block;
{
int i, ii;
register t, j, k;

/*
* First, permute the bits in the input
*/
for (j=0; j<64; j++)
L[j] = block[IP[j]-1];

So it was probably in many versions of unix for at least a decade.

-- Richard

--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 21 '07 #29
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.orgw rote:
>Quite so, but we know that they are adjacent on the OP's system (given
the assumptions I listed). Of course, it's possible that adding the
casts to char * may change that, but I doubt it.
>The assumptions you listed are not sufficient to guarantee that the
objects are adjacent. It's likely that they are, but even then
there's no reason to assume that the result of the pointer subtraction
will be positive rather than negative.
We know from the original post that the result is 1 without the casts
to char *. So unless sizeof(char *) is negative (an interesting idea)
the difference after casting will also be positive.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 21 '07 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
3413
by: Susan Baker | last post by:
Hi, I'm just reading about smart pointers.. I have some existing C code that I would like to provide wrapper classes for. Specifically, I would like to provide wrappers for two stucts defined as ff: typedef struct { float *data ; int count ;
3
3458
by: ozbear | last post by:
This is probably an obvious question. I know that pointer comparisons are only defined if the two pointers point somewhere "into" the storage allocated to the same object, or if they are NULL, or one-past the end of the object as long as it isn't dereferenced. I use "object" in the standard 'C' sense. Is there some special dispensation given to comparing two pointers
9
5068
by: Mikhail Teterin | last post by:
Hello! I'd like to have a variable of a pointer-to-function type. The two possible values are of type (*)(FILE *) and (*)(void *). For example: getter = straight ? fgetc : gzgetc; nextchar = getter(file); What type should I give to `getter' so that the compiler does not issue
12
4095
by: Lance | last post by:
VB.NET (v2003) does not support pointers, right? Assuming that this is true, are there any plans to support pointers in the future? Forgive my ignorance, but if C# supports pointers and C# and VB.NET get compiled into the same code, then I don't understand why VB.NET can't support pointers Thanks for any info Lance
14
2839
by: Alf P. Steinbach | last post by:
Not yet perfect, but: http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip To access the table of contents, use the "Bookmarks" tab in Adobe Acrobat. Comments, corrections, praise, nits, etc., are still welcome!
92
5134
by: Jim Langston | last post by:
Someone made the statement in a newsgroup that most C++ programmers use smart pointers. His actual phrase was "most of us" but I really don't think that most C++ programmers use smart pointers, but I just don't know. I don't like them because I don't trust them. I use new and delete on pure pointers instead. Do you use smart pointers?
4
3516
by: Josefo | last post by:
Hello, is someone so kind to tell me why I am getting the following errors ? vector_static_function.c:20: error: expected constructor, destructor, or type conversion before '.' token vector_static_function.c:21: error: expected constructor, destructor, or type conversion before '.' token
25
13063
by: J Caesar | last post by:
In C you can compare two pointers, p<q, as long as they come from the same array or the same malloc()ated block. Otherwise you can't. What I'd like to do is write a function int comparable(void *p, void *q) that will take any two pointers and decide whether they can be compared or not. I really can't think how to do this - any suggestions?
54
12024
by: Boris | last post by:
I had a 3 hours meeting today with some fellow programmers that are partly not convinced about using smart pointers in C++. Their main concern is a possible performance impact. I've been explaining the advantages of smart pointers endlessly (which are currently used in all our C++ software; we use the Boost smart pointers) as I'm seriously concerned that there is a shift to raw pointers. We are not developing system software but rather...
2
2988
by: StevenChiasson | last post by:
For the record, not a student, just someone attempting to learn C++. Anyway, the problem I'm having right now is the member function detAddress, of object controller. This is more or less, your standard dynamic address book program. Adding, and listing work just fine. However, deleting, editing and viewing relies on member function retAddress. This function returns an array of pointers that are pointing to created objects. In action, all it...
0
9686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9540
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10475
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10222
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4139
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.