Quote:
Originally Posted by Alan Anderson
I don't understand the point (!) of your example. What part of it should I focus on? None of it appears to show me a reason for preferring to use explicit pointers.
|
I generated assembly for both of the examples with the relevant instructions bolded
Quote:
Originally Posted by Chris27
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 }
|
Code:
.L2:
cmpl $9, -12(%ebp)
jg .L3
movl -12(%ebp), %eax
sall $2, %eax
addl -4(%ebp), %eax
movl %eax, -8(%ebp)
leal -12(%ebp), %eax
incl (%eax)
jmp .L2
.L3:
Quote:
Originally Posted by The Lucas
Code:
1 #include <stdlib.h>
2
3 int main()
4 {
5 int *array = malloc(10 * sizeof(int));
6 int *ptr = array;
7 int i;
8
9 for(i = 0; i < 10; i++)
10 ptr++;
11
12 return 0;
13 }
|
Code:
.L2:
cmpl $9, -12(%ebp)
jg .L3
leal -8(%ebp), %eax
addl $4, (%eax)
leal -12(%ebp), %eax
incl (%eax)
jmp .L2
.L3:
So 4 instructions are necessary for
ptr = array + i; and only 2 instructions for
ptr++; in this assembly language.
Quote:
Originally Posted by Alan Anderson
Isn't pass by reference exactly what Java lets you do in such cases? I guess I'm completely failing to understand what you're trying to explain here.
|
I Googled "java swap" and
this site explains it pretty well. Basically when you pass by reference to a function in Java it gives the function a new (different) reference to the object and there is no way to change the original reference in the passing function. In C++, the pointer is like an absolute reference (memory location) that is the same everywhere and you can even use pointers to pointers (no references to references in Java).