#include <iostream>
using namespace std;
typedef struct
{
char streetName[5];
} RECORD;
int main()
{
RECORD r;
cin >> r.streetName;
cout << r.streetName << endl;
}
When I run this program, if I enter in more than 5 characters, the output will show the whole string I entered. It does not truncate at 5 characters. Why is that?
How can I get this to work correctly?
The maximum index value of most arrays, therefore, is one less than its numerical value. It's same with a string, but since it has an extra character at the end, it gets incremented by one. So, the string length is the same as the number of characters in it.
The maximum allowable array size is 65,536 bytes (64K). Reduce the array size to 65,536 bytes or less. The size is calculated as (number of elements) * (size of each element in bytes).
Arrays cannot be resized. Blocks of memory can. You can declare char (*my_test)[10]; to create a pointer to an array of 10-chars and then allocate/reallocate the number of 10-char arrays in that block. Or, you can decalre char **my_test; and allocate and reallocate each individual block each pointer points to.
To change your display in Windows, select Start > Settings > Accessibility > Text size. To make only the text on your screen larger, adjust the slider next to Text size. To make everything larger, including images and apps, select Display , and then choose an option from the drop-down menu next to Scale.
You are overflowing the buffer. Put another char array after streetName and you will likely find that it gets the rest of the characters. Right now you are just corrupting some memory on your stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With