Re: arrays, pointers
From: Doug Harrison [MVP] (dsh_at_mvps.org)
Date: 02/18/04
- Next message: Kyle: "Re: arrays, pointers"
- Previous message: Arnaud Debaene: "Re: VC6 vs VC.net"
- In reply to: Kyle: "Re: arrays, pointers"
- Next in thread: Doug Harrison [MVP]: "Re: arrays, pointers"
- Reply: Doug Harrison [MVP]: "Re: arrays, pointers"
- Reply: Lucas Galfaso: "Re: arrays, pointers"
- Reply: Hendrik Schober: "Re: arrays, pointers"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 18 Feb 2004 15:49:04 -0600
Kyle wrote:
>the point is, i read/heared somewhere, that ops on pointers are faster than
>those performed on arrays
Your original post was:
>int an_int, *array;
>array = new int[n];
>
> //would i want to do:
>an_int = array[i];
> //or rather:
>an_int = *(array+i);
> //and why
If "array" is a real array, or just a pointer as above, they mean the same
thing. In fact, the former is defined in terms of the latter. However, Per
Nilsson mentioned that this equivalence doesn't extend to types like
std::vector, which support only the subscripted syntax.
Above, the variable "array" is a pointer, which you've set to point at the
first element of a dynamically allocated array of int. Suppose it were a
real array, declared, say, like this:
int array[N]; // N being a constant
Then these expressions are still equivalent:
1. an_int = array[i];
2. an_int = *(array+i);
First, the compiler transforms (1) into (2). Then, because "array" is an
actual array, it performs the standard array-to-pointer conversion, which
yields a pointer to its first element. You can think of this as the compiler
creating a temporary pointer variable, assigning it the address of the
array's first element, and using this temporary pointer in the arithmetic.
As for your efficiency concerns, there's no difference between subscripting
and pointer arithmetic, as the former is transformed at compile-time into
the latter. There are potential differences between using pointers vs.
arrays, but that's very much dependent on your usage pattern and compiler. A
compiler might recognize this idiom:
while (*s++ = *t++) ...
but not the subscripted equivalent. As ever, I'd let clarity be my guide,
and if there's any doubt, profile.
-- Doug Harrison Microsoft MVP - Visual C++
- Next message: Kyle: "Re: arrays, pointers"
- Previous message: Arnaud Debaene: "Re: VC6 vs VC.net"
- In reply to: Kyle: "Re: arrays, pointers"
- Next in thread: Doug Harrison [MVP]: "Re: arrays, pointers"
- Reply: Doug Harrison [MVP]: "Re: arrays, pointers"
- Reply: Lucas Galfaso: "Re: arrays, pointers"
- Reply: Hendrik Schober: "Re: arrays, pointers"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|