Concept

How do you access array elements safely in C?

ComputerScienceOne / Basic Usage

"Once an array has been created, its elements can be accessed using indexing. C uses the standard 0-indexing scheme so the first element is at index 0, the second at index 1, etc. Indexing an element involves using the square bracket notation and providing an index. Once indexed, an array element can be treated as a normal variable and can be used with other operators such as the assignment operator or comparison operators.\n\narr[0] = 42;\n\nif(arr[4] < 0) {\n\nprintf(\"negative!\n\n\");\n\n}\n\nprintf(\"arr[1] = %d\n\n\", arr[1]);\n\nRecall that an index is actually an offset. The compiler and system know exactly how many bytes each int element takes and so an index i calculates exactly how many bytes from the first element the i-th element is located at. Consequently it is possible to index elements that are beyond the range of the array. For example, arr[-1] or arr[5] would attempt to access an element immediately before the first element and immediately after the last element. Obviously, these elements are not part of the array.\n\nIf these out-of-bound elements represent a memory space that does not belong to our program, then it is likely that a segmentation fault will occur and terminate our program. However, it is also likely that the memory space surrounding our array does belongs to our program. Still, accessing those blocks of memory may not give us meaningful values and modifying them could corrupt other variable values or generally lead to undefined behavior. It is our responsibility as programmers to write code that does not go beyond the bounds of an array.\n\nHow can we keep track of the size of the array so that we do not access elements after the last element? With C the responsibility again falls to us. We must always have secondary variables that store the size of an array. If we pass an array to a function, we must also pass a “size” parameter so that the function knows how big the array is."

Related Ideas

How do you access array elements safely in C? | ComputerScienceOne | Bifalgorithm | Bifalgorithm