473,799 Members | 3,163 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
In article <GW************ ***@newssvr25.n ews.prodigy.net >,
Daniel Rudy <ZGNydWR5QHBhY2 JlbGwubmV0wrote :
>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.
>Not necessarily. Did you see Flash Gordon's post (Message ID:
<an*********** *@news.flash-gordon.me.uk>) when he ran it on a AIX 5.3
machine? It gave -1 as the answer. Two different platforms gives two
different answers, both compiled with gcc.
Read what I wrote. "We know from the original post that the result is
1". The original poster ran the program and that's what he got. I
then said "If the system the OP is using [has various properties]
....". I am describing what the OP's system will produce, not what
some other gcc system will produce.
>As most of us here know, undefined behavior is undefined behavior:
anything can happen, any result is possible. It all depends on your
implementation , compiler, and platform.
That's why I spelt out various assumptions. Given those assumptions,
what I said is true.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 23 '07 #61
Daniel Rudy wrote:
At about the time of 2/20/2007 10:11 PM, Praveen stated the following:
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.

It's undefined behavior for reasons that others have pointed out.

In this case, x and y are placed ajacent in memory, so the difference is
1 since you are subtracting int pointers. Some people here have had -1
on their systems.

strata:/home/dr2867/c/test 1062 $$$ ->cat ub001.c

#include <stdio.h>

int main(void)
{
int x;
int y;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1 - p2);
The ld format specifier might be a safer option. If you know your
implementation supports C99, then the tx or td format specifier would
be appropriate.
printf("p1 = %0#x\np2 = %0#x\n", (unsigned int)p1, (unsigned int)p2);
Why not simply?

printf("p1 = %p\np2 = %p\n", (void *)p1, (void *)p2);

Feb 23 '07 #62
ri*****@cogsci. ed.ac.uk (Richard Tobin) writes:
In article <GW************ ***@newssvr25.n ews.prodigy.net >,
Daniel Rudy <ZGNydWR5QHBhY2 JlbGwubmV0wrote :
>>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.
>>Not necessarily. Did you see Flash Gordon's post (Message ID:
<an********** **@news.flash-gordon.me.uk>) when he ran it on a AIX 5.3
machine? It gave -1 as the answer. Two different platforms gives two
different answers, both compiled with gcc.

Read what I wrote. "We know from the original post that the result is
1". The original poster ran the program and that's what he got. I
then said "If the system the OP is using [has various properties]
...". I am describing what the OP's system will produce, not what
some other gcc system will produce.
>>As most of us here know, undefined behavior is undefined behavior:
anything can happen, any result is possible. It all depends on your
implementatio n, compiler, and platform.

That's why I spelt out various assumptions. Given those assumptions,
what I said is true.
I, for one, did not assume that the presented output was part of your
assumptions. I though you were drawing a conclusion based only on
your stated assumptions. It's entirely possible I misread your
article; I'm too lazy to go back and check.

--
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 23 '07 #63
"santosh" <sa*********@gm ail.comwrites:
Daniel Rudy wrote:
[...]
>#include <stdio.h>

int main(void)
{
int x;
int y;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1 - p2);

The ld format specifier might be a safer option.
"%ld" is really no safer than "%d". You need to convert the ptrdiff_t
result to a known type before printing it:

printf("%ld\n", (long)(p1 - p2));

--
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 23 '07 #64
At about the time of 2/23/2007 9:34 AM, santosh stated the following:
Daniel Rudy wrote:
>At about the time of 2/20/2007 10:11 PM, Praveen stated the following:
>>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.
It's undefined behavior for reasons that others have pointed out.

In this case, x and y are placed ajacent in memory, so the difference is
1 since you are subtracting int pointers. Some people here have had -1
on their systems.

strata:/home/dr2867/c/test 1062 $$$ ->cat ub001.c

#include <stdio.h>

int main(void)
{
int x;
int y;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1 - p2);

The ld format specifier might be a safer option. If you know your
implementation supports C99, then the tx or td format specifier would
be appropriate.
You snipped my gcc command line, but I use -ansi and -std=c89 for my
language options. Gcc didn't give any warnings about my code, so I left
it as is.
> printf("p1 = %0#x\np2 = %0#x\n", (unsigned int)p1, (unsigned int)p2);

Why not simply?

printf("p1 = %p\np2 = %p\n", (void *)p1, (void *)p2);
Because I was experimenting with it.

--
Daniel Rudy

Email address has been base64 encoded to reduce spam
Decode email address using b64decode or uudecode -m

Why geeks like computers: look chat date touch grep make unzip
strip view finger mount fcsk more fcsk yes spray umount sleep
Feb 24 '07 #65
Daniel Rudy wrote, On 24/02/07 12:43:
At about the time of 2/23/2007 9:34 AM, santosh stated the following:
>Daniel Rudy wrote:
>>At about the time of 2/20/2007 10:11 PM, Praveen stated the following:
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.

It's undefined behavior for reasons that others have pointed out.

In this case, x and y are placed ajacent in memory, so the difference is
1 since you are subtracting int pointers. Some people here have had -1
on their systems.

strata:/home/dr2867/c/test 1062 $$$ ->cat ub001.c

#include <stdio.h>

int main(void)
{
int x;
int y;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1 - p2);
The ld format specifier might be a safer option. If you know your
implementati on supports C99, then the tx or td format specifier would
be appropriate.

You snipped my gcc command line, but I use -ansi and -std=c89 for my
language options. Gcc didn't give any warnings about my code, so I left
it as is.
The compiler is not required to warn about miss-matches between format
specifiers and the corresponding options, with gcc I believe there is an
extra switch that will make it diagnose simple cases, but it cannot test
all possibilities. Also, the type might happen to be int, it just is not
guaranteed.
>> printf("p1 = %0#x\np2 = %0#x\n", (unsigned int)p1, (unsigned int)p2);
Why not simply?

printf("p1 = %p\np2 = %p\n", (void *)p1, (void *)p2);

Because I was experimenting with it.
As long as there is a good reason ;-)
Using unsigned long would have been closer to portable, since on some 64
bit systems pointers are 64 bit but int and unsigned int are only 32
bit. %p as suggested above is of course always suitable.
--
Flash Gordon
Feb 24 '07 #66
At about the time of 2/23/2007 9:05 AM, Richard Tobin stated the following:
In article <GW************ ***@newssvr25.n ews.prodigy.net >,
Daniel Rudy <ZGNydWR5QHBhY2 JlbGwubmV0wrote :
>>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.
>Not necessarily. Did you see Flash Gordon's post (Message ID:
<an*********** *@news.flash-gordon.me.uk>) when he ran it on a AIX 5.3
machine? It gave -1 as the answer. Two different platforms gives two
different answers, both compiled with gcc.

Read what I wrote. "We know from the original post that the result is
1". The original poster ran the program and that's what he got. I
then said "If the system the OP is using [has various properties]
...". I am describing what the OP's system will produce, not what
some other gcc system will produce.
Sorry, I didn't catch it until after I hit the send button.
>As most of us here know, undefined behavior is undefined behavior:
anything can happen, any result is possible. It all depends on your
implementation , compiler, and platform.

That's why I spelt out various assumptions. Given those assumptions,
what I said is true.

-- Richard


--
Daniel Rudy

Email address has been base64 encoded to reduce spam
Decode email address using b64decode or uudecode -m

Why geeks like computers: look chat date touch grep make unzip
strip view finger mount fcsk more fcsk yes spray umount sleep
Feb 26 '07 #67

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
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
10026
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
9068
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
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...
2
3757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.