#include<stdio.h>
# define A 10

const short LINE_SIZE = 255; 

main(){
  char a[LINE_SIZE + 1] =  " ";  //Error here...why is this an error??
  char b[A]=""; //no problem here

  printf("%d",sizeof(a));
  printf("%s",a);
}

The first line puts a space into the first char of a, and a zero into the second char. All other elements of a are uninitialised. Hence the compiler diagnostic (which will usually be a warning, not an error).

The second line initialises the array b with a zero byte (that's what "" yields in memory). If one element of an array is initialised to zero, all elements are (i.e. the whole array is initialised)

Wow, grumpier. That was total BS. :icon_rolleyes:

>The first line puts a space into the first char of a, and a zero into
>the second char. All other elements of a are uninitialised.
String literal initialization is equivalent to a brace enclosed initialization list. char a[LINE_SIZE + 1] = " "; is essentially syntactic sugar for char a[LINE_SIZE + 1] = {' ', '\0'}; , so assuming the initialization is allowed (which it isn't, hence the error), all elements will be initialized in a predictable manner.

>If one element of an array is initialised to zero, all
>elements are (i.e. the whole array is initialised)
Rather, if there are fewer initializers than elements in the array, all uninitialized elements are implicitly initialized to the equivalent of {0} for that type. The explicit initializer doesn't have to be "zero", whatever you meant by that.

>char a[LINE_SIZE + 1] = " "; //Error here...why is this an error??
It's an error because const in C doesn't denote a compile-time constant. Therefore a is a variable length array (in C99). The C99 standard explicitly disallows initialization of variable length arrays. Because this is a constraint violation, an error is required. You fix it by doing an assignment rather than an initialization:

#include <string.h>

int main ( void )
{
  int x = 10;
  int a[x];

  strcpy ( a, " " );

  /* ... */

  return 0;
}

>char b[A]=""; //no problem here
A is a compile-time constant because it's replaced with 10 by the preprocessor. This means that b is a regular array and initialization is supported.

>main(){
Note that this is also a constraint violation in C99, so your compiler isn't strictly conforming to either C89 (where implicit int is allowed but VLAs aren't) or C99 (where VLAs are allowed but not implicit int) with the switches you're giving it. Presumably you're relying on C89 and a compiler's variable length array extension, which means the details of my explanation may be different, but the underlying problem appears to be the same.

Wow, grumpier. That was total BS. :icon_rolleyes:

What can I say? I was tired. My sig also applies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.