2

This is a "how does it work" question. Based on my understanding, you have to initialize a non-dynamic array with a constant number of elements (int intarr[5]) or your array will write over blocks of memory that might be allocated for something else.

So why is it that you can initialize a string array (string strArray[]) without any elements?

Example:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string s[] = {"hi", "there"};

cout << s[0] << s[1];
cin >> s[10]; //why is this ok?
cout << s[10];

return 0;
}
4

2 回答 2

5

As a feature C++ (and C) allows you to declare an array without specifying the number of elements if you specify an initializer for it. The compiler will infer the number of elements that's needed.

So for

   int intarr[] = { 1,2,3,4,5};

The compiler will see that the array need to have room for 5 ints, and this is will be exactly the same as if you stated:

int intarr[5] = {1,2,3,4,5};

A string array is just the same;

 string s[] = {"hi", "there"};

is the same as if you wrote

 string s[2] = {"hi", "there"};

Your code has a serious bug though;

string s[] = {"hi", "there"};

cout << s[0] << s[1];
cin >> s[10]; //why is this ok?

cin >> s[10]; is absolutely NOT ok. The array s has only 2 elements, and even if the compiler does not generate an error, you cannot use s[10] Doing so results in undefined behavior - so it could appear to work, or it could crash, or it could do anything.

于 2013-09-17T20:29:22.260 回答
0

You can use string strArray[] in 2 ways

string strArray[] = {"apple","banana"};

or

void function(string strArray[]) {
    ...
}

In the first case, the size of the array is automatically determined by the number of initializers (2). In the second case, the size of the array is not needed because it is a formal argument.

Other than that, you must declare a size to the array. It doesn't matter if it is based on string or int.

If you are writing to s[10] in your example but only have 2 elements, you are writing to unallocated memory and the program behavior is undefined. It may not crash, but later on something bad will happen.

于 2013-09-17T20:27:53.073 回答