Not sure exactly why using pointers would be necessary here

Hiya!
I’ve been taking the Learn C course and have been working on the section regarding memory and pointers → here. Codecademy provides this example for using pointers to iterate through an array and print the results:

int arr[10] = {2, 4, 7, 1, 10, 3, 11, 6, 20, 5};
int* ptr = &arr[0]; 
 
for(int i = 0; i < 10; i++){
  printf("%i\n", *ptr);
  ptr++;
}

However the same effect could be achieved (much more simply in my opinion) by doing this instead without using pointers and accessing the required indexes directly, which is shown in this lesson from the arrays and strings section → here :

int arr[10] = {2, 4, 7, 1, 10, 3, 11, 6, 20, 5};

for(int i = 0; i < 10; i++){
  printf("%i\n", arr[i]);
}

Is there any reason why it would be necessary (or even just good practise/recommended) to use pointers as shown in that lesson instead of using something a lot simpler to read/understand as it seems to me like they would add needless complexity? Or is it more just that you could use pointers there and it was a good situation to demonstrate them and in any actual situation where you would want to iterate through an array both would be perfectly acceptable.

Thanks!
Lyall

I’ll preface it with a caveat that I don’t know C well enough to say with any certainty but it seems like an example (perhaps a wee test about how well you understand pointers), you can equate arr[index] to *(arr + index). If you’re curious you can find some back and forth about speed of pointers vs. indexing but I think general advice is to use an index in most situations (the compiler probably dwarfs any attempts to pre-emptively optimise you make anyway).

You might find the pointers used a little more often in functions, e.g. where you wish to pass in an array as you only have a reference to the start of the array (array to pointer decay). I’ve seen some debate about whether creating an additional variable is worthwhile at this point since you already have a pointer; the same is true when you want to make further use of a pointer (why convert just to convert back again?).

Most everything I’ve seen just suggests going for what’s sensible/readable at any particular moment in time, if your profiling flags something up as a sticking point then you can worry about trying to outdo the compiler :laughing:.

1 Like

Ahh yeah that makes sense, thanks tgrtim! :smile:

1 Like

It’s almost all second hand info so take it with a hefty pinch of salt :wink:, that’s at least how I’ve interpreted the situation. Happy to be corrected otherwise.

1 Like