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
Richard Heathfield <rj*@see.sig.in validwrites:
Praveen said:
>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>
Even with the #include, the behavior is undefined (a) because of the
invalid pointer subtraction, and (b) because printf with "%d" expects
an argument of type int, and pointer subtraction yields a value of
type ptrdiff_t.

Here's a more nearly portable version of the above program:

#include <stdio.h>
int main(void)
{
struct {
int x;
int y;
} s;
int *p1 = &s.x;
int *p2 = &s.y;
printf("%ld\n", (long)(p1-p2));
return 0;
}

The output on my system is "-1".

But even this program invokes undefined behavior, since pointer
subtraction is defined only for pointers to elements of the same array
(or just past the end of the array, with a single object treated as a
one-element array). For the above program, the compiler could
conceivably insert a padding byte between x and y, making the
subtraction meaningless.

Note that any object can be treated as an array of characters, so my
version of the program can be "fixed" by using char* rather than int*
(with appropriate conversions).

--
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 #31
Keith Thompson wrote:
#include <stdio.h>
int main(void)
{
struct {
int x;
int y;
} s;
int *p1 = &s.x;
int *p2 = &s.y;
printf("%ld\n", (long)(p1-p2));
return 0;
}

The output on my system is "-1".

But even this program invokes undefined behavior, since pointer
subtraction is defined only for pointers to elements of the same array
(or just past the end of the array, with a single object treated as a
one-element array). For the above program, the compiler could
conceivably insert a padding byte between x and y, making the
subtraction meaningless.
The compiler could conceivably insert a padding byte
between x and y, only if sizeof(int) equals one.
x and y each have to have a valid address for type int.

--
pete
Feb 22 '07 #32
On Feb 21, 5:13 am, rich...@cogsci. ed.ac.uk (Richard Tobin) wrote:
In article <EomdneUB5ItI30 HYnZ2dnUVZ8tPin ...@bt.com>,
Richard Heathfield <r...@see.sig.i nvalidwrote:
>>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".

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).
That assumes that the objects are allocated or subtracted from
automatic memory consecutively.
I don't think that there is any requirement for that to happen.

Feb 22 '07 #33
pete <pf*****@mindsp ring.comwrites:
Keith Thompson wrote:
>#include <stdio.h>
int main(void)
{
struct {
int x;
int y;
} s;
int *p1 = &s.x;
int *p2 = &s.y;
printf("%ld\n", (long)(p1-p2));
return 0;
}

The output on my system is "-1".

But even this program invokes undefined behavior, since pointer
subtraction is defined only for pointers to elements of the same array
(or just past the end of the array, with a single object treated as a
one-element array). For the above program, the compiler could
conceivably insert a padding byte between x and y, making the
subtraction meaningless.

The compiler could conceivably insert a padding byte
between x and y, only if sizeof(int) equals one.
x and y each have to have a valid address for type int.
You're assuming that an N-byte int has to be aligned on an N-byte
boundary. That's not necessarily the case. Suppose sizeof(int)==4,
and the struct layout is:

x at offset 0, 4 bytes
padding at offset 4, 1 bytes
y at offset 5 4 bytes

There's probably no good reason for a compiler to do this, but nothing
in the standard forbids it.

--
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 22 '07 #34
Keith Thompson wrote:
>
pete <pf*****@mindsp ring.comwrites:
Keith Thompson wrote:
#include <stdio.h>
int main(void)
{
struct {
int x;
int y;
} s;
int *p1 = &s.x;
int *p2 = &s.y;
printf("%ld\n", (long)(p1-p2));
return 0;
}

The output on my system is "-1".

But even this program invokes undefined behavior, since pointer
subtraction is defined only for pointers
to elements of the same array
(or just past the end of the array,
with a single object treated as a
one-element array). For the above program, the compiler could
conceivably insert a padding byte between x and y, making the
subtraction meaningless.
The compiler could conceivably insert a padding byte
between x and y, only if sizeof(int) equals one.
x and y each have to have a valid address for type int.

You're assuming that an N-byte int has to be aligned on an N-byte
boundary.
Yes, I was.
That's not necessarily the case.
I forgot about that.

--
pete
Feb 22 '07 #35
Richard Heathfield wrote:
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.
Minor practical exception - a system with parity memory bits may
actually use CHAR_BIT+1 storage bits. However, those extra bits
are never visible to the programmer. Similarly for ECC memory.
Yet evil values can bring the system to a screeching halt.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Feb 22 '07 #36
CBFalconer said:
Richard Heathfield wrote:
>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.

Minor practical exception - a system with parity memory bits may
actually use CHAR_BIT+1 storage bits.
It is required to behave "as if" each byte has CHAR_BIT bits.
However, those extra bits
are never visible to the programmer.
In which case it's "as if" they don't exist. So my answer stands.
Similarly for ECC memory.
Yet evil values can bring the system to a screeching halt.
One of the jobs of a C programmer is to ensure that evil values never
happen.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 22 '07 #37
Richard Heathfield wrote:
CBFalconer said:
>Richard Heathfield wrote:
>>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.

Minor practical exception - a system with parity memory bits may
actually use CHAR_BIT+1 storage bits.

It is required to behave "as if" each byte has CHAR_BIT bits.
>However, those extra bits are never visible to the programmer.

In which case it's "as if" they don't exist. So my answer stands.
>Similarly for ECC memory.
Yet evil values can bring the system to a screeching halt.

One of the jobs of a C programmer is to ensure that evil values
never happen.
In the posited case such action is out of the reach of the
programmer. The system is protecting against hardware faults. Yet
the extra bits exist, and can often be seen via adroit manipulation
of your handy 'scope or data analyzer.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Feb 22 '07 #38
santosh wrote:
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);
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.
Perhaps I haven't made myself clear enough. I agree with all what you
have written above. You have said more or less what I meant to say :).

The OP is a beginner and as a fresh in C he/she expects that the
subtraction of addresses of two objects yields the distance between them
measured in *bytes*. And that's why he/she is surprised at getting the
value "1" from the program. And he/she would be as much surprised if the
two object were the part of the same array.
Feb 22 '07 #39
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
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.
Feb 22 '07 #40

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...
1
10375
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
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
5686
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4331
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
3860
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
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.