473,809 Members | 2,769 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 2740
rafalp wrote:
santosh wrote:
>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
implementati on 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.

I'm not making anywhere the assumption that they are adjacent. My point
was to explain to the OP that for two given objects o1, o2 of the same type

&o1 - &o2 := (addressof(o1) - addressof(o2)) / sizeof(objects)

That's all.
Even that isn't guaranteed.

(&o1 - &o2) could be (42) and ((char*)&o1 - (char*)&o2) could be
('bananas'). Subtracting pointers to two objects that aren't part of
some other object (i.e. array, structure, union, etc.) is undefined.
--
Clark S. Cox III
cl*******@gmail .com
Feb 22 '07 #41
rafalp wrote:
santosh wrote:
<snip>
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.

I'm not making anywhere the assumption that they are adjacent. My point
was to explain to the OP that for two given objects o1, o2 of the same type

&o1 - &o2 := (addressof(o1) - addressof(o2)) / sizeof(objects)

That's all.
That holds true only for two given objects o1, o2 of the same type
*and part of an array*. Two arbitrary objects can be placed anywhere
in memory and hence the difference of their addresses , (which invokes
undefined behaviour), need not be any expected value at all. The two
objects in OP's post were two arbitrary objects, hence his expectation
of any sensible output as well as your explanation based on an
assumption that the OP may not know about, are both wrong.

Feb 22 '07 #42
santosh wrote:
>
That holds true only for two given objects o1, o2 of the same type
*and part of an array*. Two arbitrary objects can be placed anywhere
in memory and hence the difference of their addresses , (which invokes
undefined behaviour), need not be any expected value at all. The two
objects in OP's post were two arbitrary objects, hence his expectation
of any sensible output as well as your explanation based on an
assumption that the OP may not know about, are both wrong.
OK. That's what C standard says.
I'm pretty sure that compilers perform the same operations when
subtracting any two pointers, no matter if they are related or not.
But still subtracting unrelated pointers is of little sense to me.
Feb 22 '07 #43
Clark S. Cox III wrote:
>I'm not making anywhere the assumption that they are adjacent. My point
was to explain to the OP that for two given objects o1, o2 of the same type

&o1 - &o2 := (addressof(o1) - addressof(o2)) / sizeof(objects)

That's all.

Even that isn't guaranteed.

(&o1 - &o2) could be (42) and ((char*)&o1 - (char*)&o2) could be
('bananas'). Subtracting pointers to two objects that aren't part of
some other object (i.e. array, structure, union, etc.) is undefined.
I don't understand what you mean. (&o1 - &o2) and ((char*)&o1 -
(char*)&o2) give different results even if o1 and o2 are the part of the
same array unless sizeof(o1) == sizeof(char).
Feb 22 '07 #44
rafalp wrote:
santosh wrote:
>>
That holds true only for two given objects o1, o2 of the same type
*and part of an array*. Two arbitrary objects can be placed anywhere
in memory and hence the difference of their addresses , (which invokes
undefined behaviour), need not be any expected value at all. The two
objects in OP's post were two arbitrary objects, hence his expectation
of any sensible output as well as your explanation based on an
assumption that the OP may not know about, are both wrong.

OK. That's what C standard says.
I'm pretty sure that compilers perform the same operations when
subtracting any two pointers, no matter if they are related or not.
*Your* compiler might do that but not every compiler does that. Think of
a segmented architecture with completely separate memory spaces.
But still subtracting unrelated pointers is of little sense to me.
Of course it makes little sense--the result is completely undefined.

--
Clark S. Cox III
cl*******@gmail .com
Feb 22 '07 #45
rafalp wrote:
Clark S. Cox III wrote:
>>I'm not making anywhere the assumption that they are adjacent. My point
was to explain to the OP that for two given objects o1, o2 of the
same type

&o1 - &o2 := (addressof(o1) - addressof(o2)) / sizeof(objects)

That's all.

Even that isn't guaranteed.

(&o1 - &o2) could be (42) and ((char*)&o1 - (char*)&o2) could be
('bananas'). Subtracting pointers to two objects that aren't part of
some other object (i.e. array, structure, union, etc.) is undefined.

I don't understand what you mean. (&o1 - &o2) and ((char*)&o1 -
(char*)&o2) give different results even if o1 and o2 are the part of the
same array unless sizeof(o1) == sizeof(char).
If they are *not* part of the same array, there are no restrictions on
what either subtraction could yield, nor is there any guarantee that the
two results are related in any way (hence the "42" and "'bananas'" ).
--
Clark S. Cox III
cl*******@gmail .com
Feb 22 '07 #46
Clark S. Cox III napisał(a):
rafalp wrote:
>santosh wrote:
>>That holds true only for two given objects o1, o2 of the same type
*and part of an array*. Two arbitrary objects can be placed anywhere
in memory and hence the difference of their addresses , (which invokes
undefined behaviour), need not be any expected value at all. The two
objects in OP's post were two arbitrary objects, hence his expectation
of any sensible output as well as your explanation based on an
assumption that the OP may not know about, are both wrong.
OK. That's what C standard says.
I'm pretty sure that compilers perform the same operations when
subtracting any two pointers, no matter if they are related or not.

*Your* compiler might do that but not every compiler does that. Think of
a segmented architecture with completely separate memory spaces.
Can you think of a real that checks relate-ness of pointers prior to
subtracting them and performs two different algorithms depending on
whether they are related or not?
Feb 22 '07 #47
rafalp wrote:
Clark S. Cox III napisał(a):
rafalp wrote:
santosh wrote:
That holds true only for two given objects o1, o2 of the same type
*and part of an array*. Two arbitrary objects can be placed anywhere
in memory and hence the difference of their addresses , (which invokes
undefined behaviour), need not be any expected value at all. The two
objects in OP's post were two arbitrary objects, hence his expectation
of any sensible output as well as your explanation based on an
assumption that the OP may not know about, are both wrong.
OK. That's what C standard says.
I'm pretty sure that compilers perform the same operations when
subtracting any two pointers, no matter if they are related or not.
*Your* compiler might do that but not every compiler does that. Think of
a segmented architecture with completely separate memory spaces.

Can you think of a real that checks relate-ness of pointers prior to
subtracting them and performs two different algorithms depending on
whether they are related or not?
No. Pointer arithmetic is valid only for pointers to the same object
or objects within an array. For other cases, the behaviour is
undefined. Specific implementations will usually emit a diagnostic but
go ahead and perform the operation anyway. Whether the result makes
sense is upto the programmer. In flat memory models and for objects of
the same type and scope, it *might* make sense. Most programs don't
need such information anyway.

Feb 22 '07 #48
rafalp <{m**@gazeta.pl wrote:
Clark S. Cox III napisał(a):
rafalp wrote:
santosh wrote:
That holds true only for two given objects o1, o2 of the same type
*and part of an array*. Two arbitrary objects can be placed anywhere
in memory and hence the difference of their addresses , (which invokes
undefined behaviour), need not be any expected value at all. The two
objects in OP's post were two arbitrary objects, hence his expectation
of any sensible output as well as your explanation based on an
assumption that the OP may not know about, are both wrong.
OK. That's what C standard says.
I'm pretty sure that compilers perform the same operations when
subtracting any two pointers, no matter if they are related or not.
*Your* compiler might do that but not every compiler does that. Think of
a segmented architecture with completely separate memory spaces.

Can you think of a real that checks relate-ness of pointers prior to
subtracting them and performs two different algorithms depending on
whether they are related or not?
Who's talking about two different _algorithms_? For some computers
(e.g., under MS-DOS), subtracting a pointer in one segment from one in
another might use the same algorithm as subtracting two pointers from
the same segment, but exactly _because_ of this give "wrong", semi-
random results. For other computers, comparing a pointer in one ring to
a pointer in another ring might cause a security violation error at the
hardware level (i.e., before the C implementation can even react to it),
terminating the program with extreme prejudice.

Richard
Feb 22 '07 #49
Richard Bos wrote:
rafalp <{m**@gazeta.pl wrote:
>Clark S. Cox III napisaÅ?(a):
>>rafalp wrote:
santosh wrote:
That holds true only for two given objects o1, o2 of the same type
*and part of an array*. Two arbitrary objects can be placed anywhere
in memory and hence the difference of their addresses , (which invokes
undefined behaviour), need not be any expected value at all. The two
objects in OP's post were two arbitrary objects, hence his expectation
of any sensible output as well as your explanation based on an
assumptio n that the OP may not know about, are both wrong.
OK. That's what C standard says.
I'm pretty sure that compilers perform the same operations when
subtractin g any two pointers, no matter if they are related or not.
*Your* compiler might do that but not every compiler does that. Think of
a segmented architecture with completely separate memory spaces.
Can you think of a real that checks relate-ness of pointers prior to
subtracting them and performs two different algorithms depending on
whether they are related or not?

Who's talking about two different _algorithms_?
Actually santosh is. He said "not every compiler does that" in response
to my "compilers perform the same operations". That's why I asked.
For some computers
(e.g., under MS-DOS), subtracting a pointer in one segment from one in
another might use the same algorithm as subtracting two pointers from
the same segment, but exactly _because_ of this give "wrong", semi-
random results.
With that I fully agree. I have *not* stated anywhere in the discussion
that subtracting unrelated pointer makes any sense nor I'm defending
that thesis.
For other computers, comparing a pointer in one ring to
a pointer in another ring might cause a security violation error at the
hardware level (i.e., before the C implementation can even react to it),
terminating the program with extreme prejudice.
No, because you're not accessing memory in "another ring". Comparing
pointers is not the same as accessing memory they point to.
Feb 22 '07 #50

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

Similar topics

27
3416
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
5069
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
4099
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
2842
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
5141
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
3518
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
13065
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
12035
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
2990
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
9721
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
10633
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...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10114
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9198
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6880
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
5548
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
5686
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.