Array initialization that exceed array size

Go To Last Post
6 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm trying to figure out what happens if an array gets initialized with more elements than it's declared to hold.

char foo[4] = {0, 1, 2, 3, 4}

The above gives a compiler warning, but this

char bar[4] = {0, 1, 2, 3,}

does not. What happens in the last example? The reason I'm asking is that I have a CRC8-array declared as

//CRC-8 array from the Maxim ApNote 
unsigned char crc8_array[256] = {
0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83,
0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41,
.
.
.
0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35,
};

Notice that the author has forgotten to remove that last comma. What will this do for any other variables residing close to the array?

Thanks,

/Bo[/code]

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

There is an exception in the C standard for that last, superfluous comma. It is by definition to be ignored by a compiler.

I doubt the author forgot the last comma. That exception in the standard sometimes makes editing large array initialization less painful (copy/pasting just another line to the end without having to adjust the last line), or when using macros. It also simplifies tools that create an initializer from some data, and just generate "value, " sequences, without the need of looking ahead if they process the last bit of data.

Stealing Proteus doesn't make you an engineer.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Some compilers object to the comma.
Others will just ignore it.

If you get a complaint you just have to fix it.
If you do not, your array and surrounding variables will be safe.

Incidentally your first example should cause an error with every compiler. If you are unsure of the size of your data, use a flexible array --- char foo[] = { ... };

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

david.prentice wrote:
Some compilers object to the comma.
These compilers are broken.

Clause 6.5.7 of the C90 standard starts out as (indentation lost):

ANSI/ISO 9899-1990 wrote:

6.5.7 Initialization

Syntax

initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }

initializer-list:
initializer
initializer-list , initializer


Note the line

{ initializer-list , }

It explicitly introduces the single dangling ",". There can be a dangling "," before every closing bracket in an initializer, this includes the last closing bracket.

Stealing Proteus doesn't make you an engineer.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thank you guys! Now I don't need too worry about that array anymore.

/Bo

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Just to note that an option when providing initialisers is not to specify the array dimension. If your:

char foo[4] = {0, 1, 2, 3, 4};

were

char foo[] = {0, 1, 2, 3, 4};

The compiler would simply set aside five bytes to hold all the initialisers.

Cliff