skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search