Reputation: 89
Is char s[] = ""
advisable to read a string without knowing its size?
char s[] = "";
cin >> s;
cout << s[2]; // this is working
int k = 2;
cout << s[k]; // while this does not
Any ideas?
Upvotes: 0
Views: 75
Reputation: 10403
You are creating a char
array of length 1, containing the character '\0'
. If cin
writes anything other than an empty string to s
, it will overflow the bounds of the array, causing undefined behaviour. Do not use cin
with arrays; use string
instead.
string s;
cin >> s;
Then, you must check that the character index you use is in-bounds, or you will get undefined behaviour again.
if (k < s.size()) {
cout << s[k];
}
So no, it is not safe to access an array (or string
) without knowing its size.
Upvotes: 2
Reputation: 6916
's' is an array of 1 char. When you read from cin, anything beyond the first character writes beyond the allocated size of 's', which leads to undefined behaviour. It could well be that the 'beyond' part is actually in 'k', which would work for the first cout, but then fail after k has been initialized for the second cout.
Upvotes: 1