Quote:
Originally Posted by The Lucas
[SIDE RANT] I think you are missing the point  (sorry for the pun). The point of pointer arithmetic is to compute the address of an element (the array data structure is optional). If you can get that address by simply adding to a pointer (stored in a register) that is more efficient than computing that address by loading a symbol and adding the result of a multiplication (indexing an array using a variable).[/SIDE RANT]
|
And as I stated in my earlier post, both cases boil down to a simple lea instruction in assembly
See, here is a small piece of code I just wrote.
Code:
1 #include <stdlib.h>
2
3 int main()
4 {
5 int *array = malloc(10 * sizeof(int));
6 int *ptr;
7 int i;
8
9 for(i = 0; i < 10; i++)
10 ptr = array + i;
11
12 return 0;
13 }
and its assembly
Code:
0000000000000000 <main>:
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: 48 83 ec 20 sub $0x20,%rsp
8: bf 28 00 00 00 mov $0x28,%edi
d: e8 00 00 00 00 callq 12 <main+0x12>
12: 48 89 45 f8 mov %rax,0xfffffffffffffff8(%rbp)
16: c7 45 ec 00 00 00 00 movl $0x0,0xffffffffffffffec(%rbp)
1d: 83 7d ec 09 cmpl $0x9,0xffffffffffffffec(%rbp)
21: 7f 19 jg 3c <main+0x3c>
23: 8b 45 ec mov 0xffffffffffffffec(%rbp),%eax
26: 48 98 cltq
28: 48 c1 e0 02 shl $0x2,%rax
2c: 48 03 45 f8 add 0xfffffffffffffff8(%rbp),%rax
30: 48 89 45 f0 mov %rax,0xfffffffffffffff0(%rbp)
34: 48 8d 45 ec lea 0xffffffffffffffec(%rbp),%rax
38: ff 00 incl (%rax)
3a: eb e1 jmp 1d <main+0x1d>
3c: b8 00 00 00 00 mov $0x0,%eax
41: c9 leaveq
42: c3 retq
Alternate code
Code:
1 #include <stdlib.h>
2
3 int main()
4 {
5 int *array = malloc(10 * sizeof(int));
6 int *ptr;
7 int i;
8
9 for(i = 0; i < 10; i++)
10 ptr = &array[i];
11
12 return 0;
13 }
its assembly
Code:
0000000000000000 <main>:
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: 48 83 ec 20 sub $0x20,%rsp
8: bf 28 00 00 00 mov $0x28,%edi
d: e8 00 00 00 00 callq 12 <main+0x12>
12: 48 89 45 f8 mov %rax,0xfffffffffffffff8(%rbp)
16: c7 45 ec 00 00 00 00 movl $0x0,0xffffffffffffffec(%rbp)
1d: 83 7d ec 09 cmpl $0x9,0xffffffffffffffec(%rbp)
21: 7f 19 jg 3c <main+0x3c>
23: 8b 45 ec mov 0xffffffffffffffec(%rbp),%eax
26: 48 98 cltq
28: 48 c1 e0 02 shl $0x2,%rax
2c: 48 03 45 f8 add 0xfffffffffffffff8(%rbp),%rax
30: 48 89 45 f0 mov %rax,0xfffffffffffffff0(%rbp)
34: 48 8d 45 ec lea 0xffffffffffffffec(%rbp),%rax
38: ff 00 incl (%rax)
3a: eb e1 jmp 1d <main+0x1d>
3c: b8 00 00 00 00 mov $0x0,%eax
41: c9 leaveq
42: c3 retq
Absolutely no difference whatsoever.