简体   繁体   中英

Strange values being initialized into array

int letters[] = {['A'] = 4, ['B'] = 8, ['E'] = 3, ['I'] = 1, ['O'] = 0, ['S'] = 5};

When I initialize the array letters above, my assumption is that at the index of each capital letter, the value will be the number ie if ['A'] = 4 , then at index 'A' the value will be 4 and the rest of the values not initialized will be 0 by default.

But when I print all the values of the array letters, I am getting this output:

00000000000000000000000000000000000000000000000000000000000000000480030001000000000514303876720941309621-1392458268143038767232767-197939865932767-1979398659327670010143038792832767

I have no idea where the negative numbers are coming from.

'S' is the highest index you gave a value for and, as your encoding's apparently ASCII, the length of your array is 83 (= 0x53). Everything with smaller indexes (without an initializer) is initialized to 0 .

When you print your array, you are accessing the array out-of-bounds, which is undefined behavior.

What your program probably outputs are the values which happen to be on the stack after your array. However, as said above, there is no guarantee about what will happen.

HTH

My guess is that the code you wrote to print the array is wrong. Just tested with this:

#include <stdio.h>

int main()
{
  int letters[] = {['A'] = 4, ['B'] = 8, ['E'] = 3, ['I'] = 1, ['O'] = 0, ['S'] = 5};
  int i;

  for (i = 0; i <= 'S'; i++) {
    printf("%d\n", letters[i]);
  }

  return 0;
}

And it works fine and prints everything up to and including 5 .

You most probably are using a for loop that is structured as follows:

for ( int i = 0; i < sizeof letters; i++ ) {
    // ...
}

And the problem lies within the sizeof letters part, which gives you the size of... letters , which is not how many elements the array has. It rather is, the size of letters , that is, size of a single element times amount of elements:

sizeof letters == sizeof * letters * amountofelements;
// evaluates to 1
// assuming that amountofelements is the amount of elements that
// the array letters points to

// more: sizeof * letters is equivalent to sizeof( letters[0] )
// and the equation above is equivalent to
// sizeof( letters ) == sizeof( letters[0] ) * amountofelements;
// just in case...

So, change your for condition into the following:

for ( int i = 0; i < sizeof letters / sizeof * letters; i++ ) {
    // whatever
}

Thanks for giving me the opportunity to use my psychic powers, kek.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM