Answers

Question and Answer:

  Home  Arrays

⟩ Tell me is it better to use a pointer to navigate an array of values, or is it better to use a subscripted array name?

It's easier for a C compiler to generate good code for pointers than for subscripts.

Say that you have this:

/* X is some type */

X a[ MAX ]; /* array */

X *p; /* pointer */

X x; /* element */

int i; /* index */

Here's one way to loop through all elements:

/* version (a) */

for ( i = 0; i < MAX; ++i )

{

x = a[ i ];

/* do something with x */

}

On the other hand, you could write the loop this way:

/* version (b) */

for ( p = a; p < & a[ MAX ]; ++p )

{

x = *p;

/* do something with x */

}

 154 views

More Questions for you: