c - How to index arrays using pointers safely -


edit: if fundamentally disagree fedora guide here, please explain why approach worse in objective way classic loops. far know cert standard doesn't make statement on using index variables on pointers.

i'm reading fedora defensive coding guide , suggests following:

always keep track of size of array working with. often, code more correct when keep pointer past last element of array, , calculate number of remaining elements substracting current position pointer. alternative, updating separate variable every time when position advanced, less correct.

this means given array

int numbers[] = {1, 2, 3, 4, 5}; 

i should not use classic

size_t length = 5; (size_t = 0; < length; ++i) {     printf("%d ", numbers[i]); } 

but instead this:

int *end = numbers + 5; (int *start = numbers; start < end; ++start) {     printf("%d ", *start); } 

or this:

int *start = numbers; int *end = numbers + 5; while (start < end) {     printf("%d ", *start++); } 
  1. is understanding recommendation correct?
  2. is implementation correct?
  3. which of last 2 safer?

your understanding of text recommends correct, implementation. regarding basis of recommendation, think confusing safe correct.

it's not using pointer safer using index. argument that, in reasoning code, easier decide logic correct when using pointers. safety failure modes: happens if code incorrect (references location outside array). correctness more fundamental: algorithm provably sets out do. might correct code doesn't need safety.

the recommendation might have been influenced andrew koenig's series in dr. dobbs couple of years ago. how c makes hard check array bounds. koenig says,

in addition being faster in many cases, pointers have big advantage on arrays: pointer array element single value enough identify element uniquely. [...] without pointers, need 3 parameters identify range: array , 2 indices. using pointers, can 2 parameters.

in c, referencing location outside array, whether via pointer or index, equally unsafe. compiler not catch out (absent use of extensions standard). koenig arguing fewer balls in air, have better shot @ getting logic right.

the more complicated construction, more obvious he's right. if want better illustration of difference, write strcat(3) both ways. using indexes, have 2 names , 2 indexes inside loop. it's possible use index 1 name other. using pointers, that's impossible. have 2 pointers.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -