I wrote a program that should generate an 10x1 array of 'A,' and then process that array by deleting an element, one at a time. Couple of questions: when I set the size of the array to 10, I get 20 elements, why? Can I set the element size of an array? Why can't I use sizeof() instead of strlen()?
When I do run the full script I get this error, why? :
Unhandled exception at 0x012D6AF7 in Challenge Problems.exe: RangeChecks instrumentation code detected an out of range array access.
Also, more in general, is there an easy way to execute only a couple of lines of code without having to comment everything else out on Visual Studio 2017?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
constint size = 10;
char array[size];
int x = 0;
while (x < strlen(array)) {
array[x] = 'A';
x++;
}
cout << strlen(array) << endl;
int y = strlen(array);
while (y > 0) {
y--;
array[y] = '\0';
cout << array << endl;
}
strlen is only for determining the length of a c-style string, which is an array of chars that contains at least one '\0' within it. The position of the first '\0' indicates the end of the string, even if the char array is larger than that.
On line 5 you used strlen on an uninitialized array, which can contain any values whatsoever. That's why it didn't tell you it was 10 chars long. It searched until it found a zero byte, which apparently occurred past the end of the actual array (which is why you got that "unhandled exception" error).
An array of 10 chars can give a maximum strlen of 9, since in that case the final char must be a '\0'. The idea of a c-style string is that even though the array contains a max of 10 chars, the string may be from 0 to 9 chars long, depending on where the '\0' is. If there is no '\0' in the array, then it is an error to call strlen on it, or even to print it, since there's no way to tell where the string ends.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int main() {
constint size = 10;
char a[size];
// Fill the first 9 chars with 'A'
for (int i = 0; i < size - 1; i++)
a[i] = 'A';
// Set the 10th char to '\0' to indicate the end of the string
a[size-1] = '\0';
for (int i = size; i-- > 0; ) {
a[i] = '\0';
std::cout << i << ": " << a << '\n';
}
}