c - How can a single printf statement changes value in an array? -
the following program prints prime numbers between 1 , 10.
#include <stdio.h> int* prime(int x,int y,int* range); void main() { int *x,s=10; int i=0; x=prime(1,10,&s); for(i=0;i<s;i++) { printf("%d\n",x[i]); } } int* prime(int x,int y,int *range){ int num[100],i,j,flag,inc=0; for(i=x;i<=y;i++) { flag=1; for(j=2;j<=(i/2);j++) { if(i%j == 0) flag=-1; } if(flag==1) { num[inc]=i; inc++; } } *range=inc; //printf("$$%d$$",*range); return num; }
the output 1 2 3 5 0 in above case, if remove the comment in printf statement in prime function , give normal printf statement output 1 2 3 5 7 how possible?? what's bug here??
the compiler used gcc compiler in linux platform.
your prime()
method returns local variable num
sitting on stack, it's not in scope (aka invalid) after theprime()
call returns.
a couple of fixes:
- you might able make
num
static inprime
- you dynamically allocate
num
(remember free it) - you pass
num
prime
method.
Comments
Post a Comment