0

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;
}
3
  • You could find our by using a debugger and stepping through the code. Commented Dec 1, 2016 at 7:59
  • Additionally is -1 an exception. memset performs bytewise initialization of a data-block and a loop iterates over the elements. That means that other values than -1 (0xffffffff) would result in different states of the array. Commented Dec 1, 2016 at 8:01
  • To expand a bit on the comment by @h4x0r - this use of memset only works by accident. Try initializing the array to 2 instead of -1. Don't use memset here. In fact, in general, don't use memset. Commented Dec 1, 2016 at 13:49

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Just to murder the point. when you use memset() you're not incrementing i so the loop behaves as you expect.
Thanks purplepsycho!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.