473,406 Members | 2,377 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

This C program prints 1 - why?

main()
{
static int a[] = {1,2,3};
printf("&a[1]-&a[0]=%u\n",&a[1]-&a[0]);
}

If you compile the above program and run it prints 1.
Why?

I printed &a[0] and &a[1] separately and the difference
is 4 and not 1

Question: Huh?
Please see below:
&a[0]=133208 &a[1]=133212
&a[1]-&a[0] = 1

Nov 14 '05 #1
7 1477
> If you compile the above program and run it prints 1.
Why?


&a[1] == (a+1)
&a[1] - &a[0] == (a+1) - a == 1
See the FAQ

Yes, you get a different difference if you coerce &a[x] to
integer, but note that floats would similarly have a different
difference. As explained in this newsgroup before, C wouldn't
be C if it did this different difference differently.

James

Nov 14 '05 #2
When you use "&a[1]-&a[0]", the complier will count how many objects
between a[1] and a[0].
If you want to count how many bytes between them, you should use
"(int)&a[1]-(int)&a[0]".

bl******@gmail.com

Nov 14 '05 #3
"bluetent" <bl******@gmail.com> wrote:

[ Get a real newsreader, or learn how to use Google properly. I've had
to manually reinstate the context here, because you removed it all. ]
ra********@yahoo.com wrote:
main()
(Implicit int has been removed in C99, btw. Better get used to
explicitly writing int main(void).)
{
static int a[] = {1,2,3};
printf("&a[1]-&a[0]=%u\n",&a[1]-&a[0]);
}

If you compile the above program and run it prints 1.
Why?
When you use "&a[1]-&a[0]", the complier will count how many objects
between a[1] and a[0].


True, but...
If you want to count how many bytes between them, you should use
"(int)&a[1]-(int)&a[0]".


....wrong.
First of all, conversion of pointers to integers is
implementation-defined; the two ints you get are perhaps quite probably
sizeof(int) apart, but this is by no means guaranteed.
Second, an int is not a very good type to use for this, both because it
may not be large enough to hold the result (which would invoke UB), and
because it is signed, possibly resulting in unexpected values in rare
cases. In C99, uintptr_t is the obvious type for this; in C89, I'd use
unsigned long, which is still not ideal, but the best C89 has.
Third, the right solution is to use the properties of char pointers,
i.c., that any pointer can be reliably converted to them because chars
have alignment requirements of 1, and that subtraction of two char
pointers must result in a difference in bytes, again, because
sizeof(char) is 1. So you'd use:

printf("&a[1]-&a[0]=%u\n", (char *)&a[1]-(char *)&a[0]);

Richard
Nov 14 '05 #4
bluetent wrote on 28/12/04 :
When you use "&a[1]-&a[0]", the complier will count how many objects
between a[1] and a[0].
If you want to count how many bytes between them, you should use
"(int)&a[1]-(int)&a[0]".


I would have said

"(char *)&a[1]-(char *)&a[0]".

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++

Nov 14 '05 #5
Correct.

You may also use (char *)&a[1] - (char *)&[0]

Nov 14 '05 #6
"Novitas" <ke*@clement.name> writes:
Correct.
What's correct? Please provide enough context to allow your readers
to figure out what you're talking about without going back to the
previous message.

As it happens, the previous message was *not* correct.

"bluetent" <bl******@gmail.com> wrote:
] When you use "&a[1]-&a[0]", the complier will count how many objects
] between a[1] and a[0].
] If you want to count how many bytes between them, you should use
] "(int)&a[1]-(int)&a[0]".

Converting pointers to int doesn't necessarily give you anything
meaningful, and I've used systems where the above will not work.
You may also use (char *)&a[1] - (char *)&[0]


That's ok (except that "&[0]" should be "&a[0]").

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #7
On Tue, 28 Dec 2004 07:55:05 +0000, Richard Bos wrote:
"bluetent" <bl******@gmail.com> wrote:
....
Third, the right solution is to use the properties of char pointers,
i.c., that any pointer can be reliably converted to them because chars
any pointer that points to a valid object or else is a null pointer,
specifically not any pointer to function unless the value is a null
pointer.
have alignment requirements of 1, and that subtraction of two char
pointers must result in a difference in bytes, again, because
sizeof(char) is 1. So you'd use:

printf("&a[1]-&a[0]=%u\n", (char *)&a[1]-(char *)&a[0]);


You're passing a value of type ptrdiff_t (possibly promoted) but you told
printf() that you're passing an unsigned int which is a type it cannot be.
This is a case where a cast is appropriate

printf("&a[1]-&a[0]=%u\n", (unsigned)((char *)&a[1]-(char *)&a[0]));

It is reasonable to assume that in this case the result is represenatble
as an unsigned int, but you would have to consider other types for the
more general case.

Lawrence
Nov 14 '05 #8

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

Similar topics

7
by: Prashanth Badabagni | last post by:
Hi , I'm Prashanth Badabagni .. I have and idea how a program prints it's own source code .. void main() { FILE *P; char *file,c; strcpy(file,__FILE__); p=fopen(file,"r");
5
by: Protoman | last post by:
Here's a program I wrote that calcs the fibonacci numbers and writes them to a file, from 1-50. It prints to the screen just fine, but it only prints the last number, Fib(50) to the file. Code:...
9
by: gg | last post by:
If somebody asks me to write a program that prints itself ( quine ) can I write the following program as an answer - #include <iostream> #include <fstream> using namespace std; int main (...
1
by: tnt84 | last post by:
I want to write a program that reads a text file and prints out the word frequencies using structure but I don't know exactly what the word frequency is and how can I write that program using...
2
by: mcpacs™ | last post by:
hey guys!! arrays really makes me confused. will you help me about this?: create a program that that accepts ten positive integers from the users. The program will group and sort all even numbers...
1
Blackout
by: Blackout | last post by:
Hi, I'm new to c and need to write a program that prints the numerical value of eof but the problem is I don't even know what the numerical value of eof is or how im supposed to find it!!! I've...
4
by: Villanmac | last post by:
Ahhhh, ive missed so many lessons this year that i have to try and teach myself c++ from a book and its so hard. Usually I just read this forums to pick things up but its doing my head in trying to...
21
by: mikhal80 | last post by:
Is it possible to write a program which would print out it's own source code, using C++?
5
by: chevon1920 | last post by:
I am trying to do my assignment but I cant figure out how to get 8 data points per line to print to a file. Here is the assignment 1. Program asks the user to enter an odd number as a BASE,...
9
by: tvnaidu | last post by:
This is just small plain HTML program wtote manually (since I am new to web programming, may be some tools I can use I think), this program loaded onto microcontroller with small foot print web...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.