473,396 Members | 1,853 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,396 software developers and data experts.

Array address arithmetic

Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));
}

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression ptr =
(char*)(a + 1); i get output as 1.what is the difference between (&a + 1)
and (a + 1) in the above mentioned expression.Help guys its confusing.

--
Message posted using http://www.talkaboutprogramming.com/group/comp.lang.c/
More information at http://www.talkaboutprogramming.com/faq.html

Dec 9 '07 #1
15 1920
"vjay" <vi***********@gmail.comwrote in
news:3948456199d9a241db54852adf077d63
@localhost.talkaboutprogramming.com:
Check the code below guys
void main()


int main(void)
{
char a[5] = {1,2,3,4,5};


Unusual to store numbers in a char, but how and ever.

char *ptr;
ptr = (char*)(&a + 1);

Here you take the address of the array "a", and add one to it. This will
give you the address of the first byte after the fifth element in the
array "a".

printf("%d",*(ptr-1));

"ptr-1" leaves you with the address of the fifth element in "a".

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression
ptr = (char*)(a + 1); i get output as 1.what is the difference between
(&a + 1) and (a + 1) in the above mentioned expression.Help guys its
confusing.


Pointer arithmetic depends on the size of the "pointed to" type. The
size of the "pointed to" type in &a is "sizeof(char[5])".
--
Tomás Ó hÉilidhe
Dec 9 '07 #2
On 12ÔÂ9ÈÕ, ÏÂÎç10ʱ43·Ö, "vjay" <vijayanand...@gmail.comwrote:
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));

}

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression ptr =
(char*)(a + 1); i get output as 1.what is the difference between (&a + 1)
and (a + 1) in the above mentioned expression.Help guys its confusing.

--
Message posted usinghttp://www.talkaboutprogramming.com/group/comp.lang.c/
More information athttp://www.talkaboutprogramming.com/faq.html
try the following:
int main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)((char*)&a + 1);
printf("%d",*(ptr-1));
getchar();
}
Dec 9 '07 #3
vjay a écrit :
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));
}

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression ptr =
(char*)(a + 1); i get output as 1.what is the difference between (&a + 1)
and (a + 1) in the above mentioned expression.Help guys its confusing.
I would say it is because &a is a pointer to an array of 5 chars, and
thus (&a + 1) add the size of one array of 5 chars. It brings you one
char after the 5.
Then ptr being a pointer to a char, doing (ptr-1) brings you one char
back, right on the 5.

I think you meant (a+1). This way, it would have worked. The name of the
array is a pointer to its first element. So "a" is really a pointer to a
char, and (a+1) points to the second element of your array.

It's all due to the difference between a pointer to a char ("a"), and a
pointer to an array of chars ("&a").

Hope i'm not mistaken,
Noé
Dec 9 '07 #4
vjay wrote:
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
Don't you mean this:
ptr = (char *)(&a[0] + 1);

Didn't you get some kind of warning? What compiler are you using?
printf("%d",*(ptr-1));
}

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression
ptr = (char*)(a + 1); i get output as 1.what is the difference
between (&a + 1) and (a + 1) in the above mentioned expression.Help
guys its confusing.

Dec 9 '07 #5
vjay wrote:
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));
}

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression ptr =
(char*)(a + 1); i get output as 1.what is the difference between (&a + 1)
and (a + 1) in the above mentioned expression.Help guys its confusing.
When you add an integer n to a pointer to a given type, the result is a
new pointer pointing that n elements of that type farther down. The
expression &a has the type char(*)[5], which means it points at an
entire array of 5 chars. Therefore, when you add 1 to it, it points at
the next array of 5 characters. Converting it to char* result in a
pointer that would point at the first char of that next array. When you
subtract 1, the behavior is undefined; however, on most real-world
implementations, the actual behavior is to point at the last char of the
previous array, which contained a 5.

In the expression (a+1), the name of the array decays into a pointer to
the first element of the array, and therefore has the type char*. When
you add 1 to that pointer, it points at the next char. When you subtract
1, it goes back to pointing at the first char, as you expected.
Dec 9 '07 #6
Anthony Fremont wrote:
vjay wrote:
>Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);

Don't you mean this:
ptr = (char *)(&a[0] + 1);

Didn't you get some kind of warning? What compiler are you using?
On what basis? If you were writing the text of the warning message, what
would it say? As far as I can see, the only thing wrong with this code
is vjay's incorrect understanding of what it does.

Dec 9 '07 #7
James Kuyper wrote:
Anthony Fremont wrote:
>vjay wrote:
>>Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);

Don't you mean this:
ptr = (char *)(&a[0] + 1);

Didn't you get some kind of warning? What compiler are you using?

On what basis? If you were writing the text of the warning message,
what would it say? As far as I can see, the only thing wrong with
this code is vjay's incorrect understanding of what it does.
Thanks, I get it now, I guess I just never had a need to try such a thing
before.
Dec 9 '07 #8
vjay wrote:
>
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));
}

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression ptr =
(char*)(a + 1); i get output as 1.
what is the difference between (&a + 1)
and (a + 1) in the above mentioned expression.Help guys its confusing.
ptr == a + 5
(char*)(&a + 1) == a + 5
&a + 1 == (char(*)[5])(a + 5)


/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
char a[5] = {1,2,3,4,5};
char *ptr = (char*)(&a + 1);

if ( ptr == a + 5) {
puts("ptr == a + 5");
}
if ( (char*)(&a + 1) == a + 5) {
puts("(char*)(&a + 1) == a + 5");
}
if ( &a + 1 == (char(*)[5])(a + 5)) {
puts("&a + 1 == (char(*)[5])(a + 5)");
}
return 0;
}

/* END new.c */

--
pete
Dec 9 '07 #9
vjay wrote:
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));
}

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression ptr =
(char*)(a + 1); i get output as 1.what is the difference between (&a + 1)
and (a + 1) in the above mentioned expression.Help guys its confusing.
You've been hanging out here for a while now haven't you? Why do you not
grasp what everybody is telling you? What you have posted is not
compilable and also incorrect. Watch ..

#include <stdio.h>

int main(void)
{
char a[5] = {1, 2, 3, 4, 5};
char *ptr;
ptr = (char *) (&a + 1);
printf("%d", *(ptr - 1));
return 0;
}

Now it's compilable and correct.
Expressing &a gives an address of type 'array 5 of char'. (&a + 1) gives
the address of the 'next' array 5 of char. You cast this address to
char* and store it in ptr. This effectively points one past the end of
array a. ptr - 1 points to the end of a and *(ptr - 1) is a[4] with value 5.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Dec 9 '07 #10
"vjay" <vi***********@gmail.comwrote in message
news:39******************************@localhost.ta lkaboutprogramming.com...
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));
}

The output of the program is 5
Thanks, your post and it's replies has clarified something that I hadn't
fully grasped; in int a[5], then:

&a is not the same thing as a, when considering Type.

Apparently a is the same as &a[0] (pointer to int), &a means a pointer to
the entire array (pointer to array of 5 ints). The values however are the
same. (Although why &a doesn't decompose to &(&a[0]) is another mystery;
maybe it only decomposes when there isn't an & in front)
void main()
With quotes, this gives 5 times as many Google hits as "int main(void)".
Looks like a lot of people can't get it right.

Bart
Dec 10 '07 #11
Bart C wrote:
>
"vjay" <vi***********@gmail.comwrote in message
news:39******************************@localhost.ta lkaboutprogramming.com...
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));
}

The output of the program is 5

Thanks, your post and it's replies
has clarified something that I hadn't
fully grasped; in int a[5], then:

&a is not the same thing as a, when considering Type.

Apparently a is the same as &a[0] (pointer to int),
&a means a pointer to
the entire array (pointer to array of 5 ints).
The values however are the same.
(Although why &a doesn't decompose to &(&a[0]) is another mystery;
maybe it only decomposes when there isn't an & in front)
That's very close to being correct.

N869
6.3.2 Other operands
6.3.2.1 Lvalues and function designators

[#3] Except when it is the operand of the sizeof operator or
the unary & operator, or is a string literal used to
initialize an array, an expression that has type ``array of
type'' is converted to an expression with type ``pointer to
type'' that points to the initial element of the array
object and is not an lvalue.

--
pete
Dec 10 '07 #12
Thank you all guys now i got it.

--
Message posted using http://www.talkaboutprogramming.com/group/comp.lang.c/
More information at http://www.talkaboutprogramming.com/faq.html

Dec 10 '07 #13
"Tomás Ó hÉilidhe" <t...@lavabit.comwrote:
"vjay" <vijayanand...@gmail.comwrote
char a[5] = {1,2,3,4,5};

Unusual to store numbers in a char, ...
What else does one store in a char? ;)

--
Peter
Dec 10 '07 #14
vjay wrote:
>
Check the code below guys
void main()
{
char a[5] = {1,2,3,4,5};
char *ptr;
ptr = (char*)(&a + 1);
printf("%d",*(ptr-1));
}

The output of the program is 5

But what i expected was 1.When i replace &a with a in the expression ptr =
(char*)(a + 1); i get output as 1.what is the difference between (&a + 1)
and (a + 1) in the above mentioned expression.Help guys its confusing.
Consider:

What does it mean when you say "&something + 1"?

What is the value of "sizeof a"?

If there were a "typeof" operator, what would be "typeof a"?

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Dec 10 '07 #15
"Bart C" <bc@freeuk.comwrites:
[...]
Apparently a is the same as &a[0] (pointer to int), &a means a pointer to
the entire array (pointer to array of 5 ints). The values however are the
same. (Although why &a doesn't decompose to &(&a[0]) is another mystery;
maybe it only decomposes when there isn't an & in front)
[...]

The answers to these and a number of similar questions can be found in
section 6 of the comp.lang.c FAQ, <http://www.c-faq.com>.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 11 '07 #16

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

Similar topics

5
by: overbored | last post by:
I can do this: int asdf; int* zxcv = asdf; but not this: int asdf; int** zxcv = asdf;
4
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where...
24
by: David Mathog | last post by:
If this: int i,sum; int *array; for(sum=0, i=0; i<len; i++){ sum += array; } is converted to this (never mind why for the moment):
14
by: romayankin | last post by:
Hello All, I'm writing cross-platform code so i'm bound to standards. Here is the code I have: ~~~~~~~~~~~~~~~~~~ double **mx = new double*; for(int i = 0; i < col - 1; i++) { mx = new...
24
by: Kavya | last post by:
int main (){ int a={{1,2,3},{4,5,6}}; int (*ptr)=a; /* This should be fine and give 3 as output*/ printf("%d\n",(*ptr)); ++ptr;
5
by: Mercy | last post by:
I guess my C++ is pretty darn rusty. I was just looking over sample C++ code for practice... and I'm kind of confused about this code fragment: int sector2; int i = 3; memset(sector2,...
21
by: subramanian100in | last post by:
Suppose we have char array; C allows taking the address of array (ie &array is valid) though the element array cannot be accessed. Is this allowed for use in binary search method (as given...
2
by: subramanian100in | last post by:
From http://groups.google.com/group/comp.lang.c++/browse_frm/thread/d5da6e5e37fd194d/6e2e8424a1cfbd2b#6e2e8424a1cfbd2b the following portion is taken. "Mike Wahler"...
7
by: lovecreatesbea... | last post by:
Is it always legal to cast expressions of type of multi-dimension array to type of pointer? Including: T to T* , T to T* , T to T* , and so on... For example: int *mtxrot1d(int *p,...
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
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
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...
0
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...
0
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,...

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.