newcoder191 newcoder191 - 2 days ago 3
C++ Question

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

When I use

memset
inside the
printNGE
function I get the correct result also when I initialize the array elements to -1 in the
main()
, I get the correct result.

But when I initialize the same in the
printNGE
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.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
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;

//memset(ans,-1,sizeof(ans));

while (i<n)
{
if(s.empty() || arr[s.top()]>arr[i])
s.push(i++);
else
{
ans[s.top()]=arr[i];
s.pop(); //pop till incoming element is greater
}
}
for(i=0;i<n;i++)
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);
getchar();
return 0;
}

Answer

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

Comments