-1

What is the difference between doing int t[102][1002] = {-1}; vs running a for loop and doing

for(int i = 0; i < 102; i++)
        for(int j = 0; j < 1002; j++)
            t[i][j] = -1;

The code below does not work when the former method is used. It works only when we I loop through and initialize. Why is that?

#include<bits/stdc++.h>
using namespace std;
int t[102][1002] = {-1};
int knapstack(int wt[], int val[], int w, int n)
{
    if(n == 0 || w == 0)
        return 0;

    if (t[n][w] != -1)
        return t[n][w];

    if(wt[n-1] <= w ){
        t[n][w] = max(val[n-1] + knapstack(wt,val, w - wt[n-1],n-1) , knapstack(wt, val, w, n-1));
        return t[n][w];
    }

    if(wt[n-1] > w){
       t[n][w] = knapstack(wt,val,w,n-1); 
       return t[n][w];
    }
}

int main()
{
    int wt[] = {10, 20, 30};
    int val[] = { 60, 100, 120};
    int w = 50, n = sizeof(val)/sizeof(val[0]);
    cout<< knapstack(wt, val, w, n);
}

Akram Mohammed
  • 141
  • 1
  • 8
  • 1
    And when you used your debugger to run your program, what did you see? This is precisely what a debugger is for. If you don't know how to use a debugger this is a good opportunity to learn how to use it to run your program one line at a time, monitor all variables and their values as they change, and analyse your program's logical execution flow. Knowing how to use a debugger is a required skill for every C++ developer, no exceptions. With your debugger's help you should be able to quickly find all bugs in this and all future programs you write, without having to ask anyone for help. – Sam Varshavchik May 28 '20 at 02:48
  • `int t[102][1002] = {-1};` doesn't do what you think it does. – eesiraed May 28 '20 at 02:51
  • I also tried ```memset(t, -1, sizeof t);``` It says it expects type conversion? – Akram Mohammed May 28 '20 at 02:57
  • Ok, I ran a for loop in the int main() function ``` for(int i = 0; i < 102; i++) for(int j = 0; j < 1002; j++) t[i][j] = -1; ``` and It worked. I'll change the question. What is the difference between declaring ```t[102][1002] = {-1} ```and using the for loop to do so? – Akram Mohammed May 28 '20 at 03:03

2 Answers2

1

this only sets the first cell of the 2D array t to -1.

int t[102][1002] = {-1};

It is better to use either of these two ways

for(int i = 0; i < 102; i++)
        for(int j = 0; j < 1002; j++)
            t[i][j] = -1;

This you already know.

Other way is using memset function.

memset(t, -1, sizeof(t));
Mehant Kammakomati
  • 852
  • 1
  • 8
  • 25
0

As others have stated, you're simply setting the first element to -1. I'll offer a more C++11 alternative to memset. Should be pretty similar performance if you use -O2 compiler optimization option.

std::fill_n(&t[0][0], sizeof(t)/sizeof(int),-1);

edit: for typos

lostdev
  • 736
  • 8
  • 23