declaring static undefined size arrays in class

Why is this statement valid :

1
2
3
4
5
6
7
class Hen{
	
	static char s[];//valid
...
..
}


but not this :


1
2
3
4
5
6
7
class Hen{
	
	static char s[][];//invalid
..
..
}
because (i seem to recall) you need at least one known dimension size for a 2d array (unless you're initialising it at that point too).
Last edited on
what's the error message?
error message : an array may not have elements of this type .
?
any help!
Declare the size of the second index.
OP: Why did you not bother reading my post??
As far as I know, you will always need to declare the size of an array, unless you plan to dynamically allocate that array at run time (in which case you wouldn't declare it as an array anyway).
yeah my question is why is the rule this way , why cant I leave the 2nd dimension too , if i can leave the first , why did they omit this feature ?

static char ss[]; // wrong ouside class , right inside class
static char ss1[][] //wrong everywhere
static char ss2[][5] // wrong ouside class ,right inside clas
Last edited on
The compiler needs to know all sizes except the first one. This has technical explanations.

To access the elements in an array all you need is the memory location of the first element in the array. To access element at index i in array arr the compiler just adds the index (multiplied by the size of an element) to the memory location to get the element. This means arr[i] is the same as *(arr + i). This is also true if arr happens to be a pointer to the first element in the array. Note that the size is not involved in the calculation so it is not needed.

To be able to do pointer arithmetic the size of the array elements has to be known. If you have an array of char the compiler knows that the size is 1, if the array elements are ints the compiler knows that that the size is sizeof(int) etc.

In your example the array elements are arrays. To know the size of an array you need to know how many elements it has. That is why you need all the array sizes except the first one.

vxk wrote:
static char ss[]; // wrong ouside class , right inside class
static char ss1[][] //wrong everywhere
static char ss2[][5] // wrong ouside class ,right inside clas

Note that when you declare a static variable inside the class definition it is just a declaration. You must also define the variable outside the class definition and when you do that the compiler will force you to specify all array sizes.
Last edited on
Topic archived. No new replies allowed.