I just spent a lot of time debugging a problem that turned out to be an easy fix. In an array sort routine, in my loop, I was overshooting the array bound, apparently SOMETIMES causing my array to be contaminated with a garbage value. It was driving me nuts because sometimes it worked perfectly and sometimes it didnt. The code is below and the fix was changing "n-1" to "n-2".
My question is: Is this sort of thing something I'm just going to have to get used to in C (I am new to C ... VB would have given me an index out of bounds error and I would have had it fixed in seconds), or is my approach to the problem somehow problematic and prone to intermittent errors that are hard to find?
Maybe you should have used < instead of <= in the for.
If you use std::vector and access elements with at() you'd get an exception when you go out of boundaries.
If you use raw pointers / arrays you have to manage memory yourself and be sure that everything you do is correct
As Bazzy says your <= control provides the opportunity of exceeding array bounds and should use <.
My understanding is that a string in 'C' is [always] an array which ends with a mandatory '/0' or NUL character.The <cstring> header provides the many functions for manipulating C strings. For example strlen(s) will return the number of characters in string 's' not counting its terminating NUL character.
C strings may not be NUL-terminated, they usually are but the programmer must be sure of this before using a function that expects a \0-terminated char array