473,786 Members | 2,445 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 #1
66 2722
Praveen wrote:
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.
Because that's what your compiler gives as the answer, subtracting two
unrelated pointers is undefined behaviour.

--
Ian Collins.
Feb 21 '07 #2
On Feb 21, 11:18 am, Ian Collins <ian-n...@hotmail.co mwrote:
Praveen wrote:
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.
>>>Because that's what your compiler gives as the answer, subtracting two
unrelated pointers is undefined behaviour.
Can Some onr tell why these are unrelated?

>
--
Ian Collins.

Feb 21 '07 #3
Raman wrote:
On Feb 21, 11:18 am, Ian Collins <ian-n...@hotmail.co mwrote:
>Praveen wrote:
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.
>>>>Because that's what your compiler gives as the answer, subtracting two
>unrelate d pointers is undefined behaviour.
Can Some onr tell why these are unrelated?
They're not part of the same object [1]. (Stack frames are not objects,
even in implementations that have stack frames, from C's POV.)

[1] Which covers `malloc` results too.

--
Chris "electric hedgehog" Dollin
"Life is full of mysteries. Consider this one of them." Sinclair, /Babylon 5/

Feb 21 '07 #4
"Raman" <ra***********@ gmail.comwrote in message
news:11******** **************@ j27g2000cwj.goo glegroups.com.. .
On Feb 21, 11:18 am, Ian Collins <ian-n...@hotmail.co mwrote:
<snip OP attribution>
>>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.
>Because that's what your compiler gives as the answer, subtracting two
unrelated pointers is undefined behaviour.
Can Some onr tell why these are unrelated?
To be related they must have some common reference point - the source of the
relationship. If there is no common reference point how can there be a
relationship? The language standard will define what types of relationship
exist between different components defined in a program text.

In what way do you believe the pointers are related? What makes you believe
this? Can you find a citation in the language standard that supports this
belief?

--
Stuart
Feb 21 '07 #5
"Raman" <ra***********@ gmail.comwrites :
On Feb 21, 11:18 am, Ian Collins <ian-n...@hotmail.co mwrote:
>Praveen wrote:
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.
>>>>Because that's what your compiler gives as the answer, subtracting two
>unrelate d pointers is undefined behaviour.
Can Some onr tell why these are unrelated?
Because they point to distinct objects.

Here's what the standard says in the section on relational operators
(<, <=, >, >=) (C99 6.5.8p5):

When two pointers are compared, the result depends on the relative
locations in the address space of the objects pointed to. If two
pointers to object or incomplete types both point to the same
object, or both point one past the last element of the same array
object, they compare equal. If the objects pointed to are members
of the same aggregate object, pointers to structure members
declared later compare greater than pointers to members declared
earlier in the structure, and pointers to array elements with
larger subscript values compare greater than pointers to elements
of the same array with lower subscript values. All pointers to
members of the same union object compare equal. If the expression
P points to an element of an array object and the expression Q
points to the last element of the same array object, the pointer
expression Q+1 compares greater than P. In all other cases, the
behavior is undefined.

(A non-array object is treated as an array of one element.)

--
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 #6
Praveen said:
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.
Even if the pointer arithmetic were legal (which others have already
pointed out, so I won't belabour it here), the call to printf is not.
Whether the (undefined) result of your illegal pointer arithmetic is
reported correctly by printf is undefined, because you failed to
provide a valid function prototype within the current scope at the
point of call to a variable argument function.

Headers are not decorative. They matter. In future, if you call printf,
do this:

#include <stdio.h>

--
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 #7
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?
In pointer arithmetic the distance between two pointers is measured in
number of object of pointer's type that would fit between the memory
locations pointed by the pointers. Thus with array

int a[10]

you can access the second element by a[1] or by *(a + 1). We add 1 to
the actual pointer but in fact compiler adds 4 or sizeof(int) to the
pointer.

Hope that helps.
Feb 21 '07 #8
rafalp said:

<snip>
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.

--
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 #9
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.
Feb 21 '07 #10

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

Similar topics

27
3412
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
3457
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
2838
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
5126
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
3513
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
13060
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
12022
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
2987
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
9647
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
9492
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,...
1
10108
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
9960
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
8988
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...
0
6744
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
5397
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...
1
4064
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
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.