0

I've initialized arr to -1 when I print them every element is initialized to 0 except the first element.

This is the small code of a bigger problem. I'm just struck here

#include <bits/stdc++.h>

using namespace std;

int fibo()
{
    int static arr[100] = {-1};
    for (int i = 0; i < 100; ++i)
    {
        cout << "arr[" << i <<"] : " << arr[i] << endl;
    }
    return -2;
}

int main(void)
{  
    cout << "Result : " << fibo() << endl;
    return 0;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Ashish Siwal
  • 17
  • 1
  • 9
  • 2
    Related: https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value – Michael Feb 02 '19 at 10:50
  • The simplest thing is to stop using an array and use `static std::vector`, where the initialization semantics aren't cumbersome as with an array. – PaulMcKenzie Feb 02 '19 at 10:52
  • Did the same sir. I don't know why every element of it is not initialized to -1. – Ashish Siwal Feb 02 '19 at 10:52
  • @AshishSiwal because they are not supposed to be. You are declaring a fixed array that holds 100 values, but you are specifing only 1 value for the first element. The other elements are thus **value-initialized**, which for `int` means 0. `std::vector`, on the other hand, has a constructor that initializes all elements to the same value: `static vector arr(100, -1);` – Remy Lebeau Feb 02 '19 at 19:00

2 Answers2

1

Simplest solution -- use std::vector<int>, and the initialization of all elements becomes available to you in a very easy form (I know there are template tricks that can be done, but IMO there is no need for that level of complexity for this in your code).

Example:

#include <vector>
#include <iostream>

int fibo()
{
    static std::vector<int> arr(100,-1);
    for (int i = 0; i < 100; ++i)
    {
        std::cout << "arr[" << i <<"] : " << arr[i] << "\n";
    }
    return -2;
}

int main(void)
{  
    std::cout << "Result : " << fibo() << "\n";
    return 0;
}

Live Example

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
0
#include <bits/stdc++.h>

using namespace std;

int fibo()
{
    int static arr[100];
    for (int i = 0; i < 100; ++i)
      {
        arr[i] = -1;
      }
    for (int i = 0; i < 100; ++i)
    {
        cout << "arr[" << i <<"] : " << arr[i] << endl;
    }
    return -2;
}

int main(void)
{  
    cout << "Result : " << fibo() << endl;
    return 0;
}

Try using this code

Abu-Bakr
  • 408
  • 6
  • 12
  • I know this sir. But I'm using static array so that the value of array once initialized will not be initialized again and again during recursion. Your code will initialize my array to -1 every time the function is called. – Ashish Siwal Feb 02 '19 at 10:48