newcoder191 newcoder191 - 1 year ago 81
C++ Question

Difference between memset() and initializinng array elements using a for loop?

When I use

inside the
function I get the correct result also when I initialize the array elements to -1 in the
, I get the correct result.

But when I initialize the same in the
function using a for loop I get a wrong answer. It seems the initial value of the array elements in not changed inside the else part of the while loop for some reason? Please tell me what could be the possible reason for such discrepancies.

using namespace std;

/* arr[] of size n */

void printNGE(int arr[], int n)
int i = 0;
stack <int> s;
int ans[n];
for(i=0;i<n;i++)//Set all the elements to -1
ans[i] = -1;


while (i<n)
if(s.empty() || arr[]>arr[i])
s.pop(); //pop till incoming element is greater
printf("%d -> %d\n",arr[i],ans[i]);

int main()
int arr[]= {11, 13, 21, 3};
int i;
int n = sizeof(arr)/sizeof(arr[0]);
//int ans[n];
//for(i=0;i<n;i++)//Set all the elements to -1
// ans[i] = -1;
printNGE(arr, n);
return 0;

Answer Source

The index variable i of the for loop is not reset. Thus, the while loop won't get executed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download