-1

My system is Ubuntu

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#define LEN 16

using namespace std;

int main(){
    int a[16] = {2};
    for (int i=0; i<16; i++)
    {
        cout << a[i] << ' ';
    }
}

I compiled it by this command in terminal : g++ t1.cpp -o t1 && ./t1

but the result is

2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
a b
  • 11
  • Array initialization does exactly what you see. It sets the elements given in the initializer, and then sets all elements not specified to `0`. See [Initialization](https://en.cppreference.com/w/cpp/language/initialization) (for C++) – David C. Rankin Nov 30 '22 at 02:02
  • The answer to the "why not" is because the language specification is quite explicit about initialization, and it does not work the way you are expecting. Just use `std::fill` if you wish to populate the array with the same value. – paddy Nov 30 '22 at 02:04

2 Answers2

3

Any decent book, tutorial or class should have taught you that the definition

int a[16] = {2};

is equivalent to

int a[16] = {2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

If you want to initialize all elements to a single value you need to explicitly do it.

You can also use std::fill after definition to set every element to a value:

int a[16];
std::fill(begin(a), end(a), 2);

And some nitpicking: What you're doing is initialization, not assignment.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You've assigned a 2 to index 0 of your array.

You may wish to use std::fill.

const int size = 16;

int main() {
    int a[size];

    std::fill(a, a + size, 2);

    return 0;
}
Chris
  • 26,361
  • 5
  • 21
  • 42