开发者

output of the programme

#include<stdio.h>

void f(void)
{
    int s = 0;
    s开发者_开发百科++;
    if(s == 10)
        return;
    f();
    printf("%d ", s);
}
int main(void)
{
    f();
}

what is the output of the programme!?? i m segmentation fault ...what is it?


Since s is a local variable, each recursive call to f() gets its own copy of it. So every time s will be 1 and the you get a stack overflow exception.


The problem here is that you're not statically initializing s. So it'll always start off as 0 every time you call f(), and f() keeps calling itself over and over again but if(s == 10) is never met. The call stack eventually overflows and boom, segmentation fault.


The problem is that you're calling f recursively, without changing anything each time. You're probably getting a stack overflow.

Each time you call f, you initialize s to 0 and increment it. It will never reach 10.

What you should do is either make s a parameter to f or else make s static.


Your program is an infinite loop; you get the segmentation fault because you eventually overflow your stack.


The program goes into an infinite loop. The reason for that is : s is local to f(), so whenever f() is called, s is initialized to 0. Then it is incremented by 1, & f() is again called. This time as well, f() uses its local copy & initializes s to 0 & again calls f() recursively. This generates an infinite loop & the program generates a segmentation fault. The reason for seg fault is stack overflow due to recursive infinite calls. To remedy this, either make s static or make it global, rather than local.


How about making your variable s static?


This is a recursive function that calls itself. However, it is an infinite loop because int s = 0; resets the counter every time it is called. It will print an endless line of 0s.

Sample solution:

int main (void) {
   f(0);
}

void f (int s) {
   if (s == 10)
      return;
   printf("%d ", s);
   f(s++);
}

I'm not good with C syntax, but the idea is sound.


Infinite loop. Here is probably something similar to what you want

#include<stdio.h>

void f(int s)
{
    s++;
    if(s == 10)
        return;
    f(s);
    printf("%d ", s);
}
int main(void)
{
    f(0);
}


This might be a more interesting program:

void f(int s)
{
  s++;
  if(s == 10)
    return;
  f(s);
  printf("%d ", s);
}

int main(void) 
{
  f(0);
}

That will print:

9 8 7 6 5 4 3 2 1


The output of this program is the name of this site.

As others suggested you should declare s as static int s = 0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜