c++ - Correcting a segmentation fault -
#include <iostream> #include <stdio.h> #include <math.h> #include <stdlib.h> using namespace std; int main(){ int i=0,n,h,k; k = (int)pow(10,5); int c[k]; scanf("%d%d",&n,&h); if((n>=1 && n<=(int)pow(10,5)) && (h>=1 && h<=(int)pow(10,8))){ int arr[n]; do{ scanf("%d",&arr[i]); if(arr[i] > h){ cout<<"error !"; exit(1); } i++; }while(i!=(n-1)); i=0; do{ /*the fault occurs somewhere here, probably*/ scanf("%d",&c[i]); i++; }while(c[i]!=0); if(i>(int)pow(10,5)){ cerr<<"error !"; exit(0); } } return 0; }
i'm trying accept few numbers console on different lines using scanf() (with constraints on upper , lower limits of numbers) - problem i'm getting segmentation fault somewhere around i've put comment - can't seem figure out fault occurs - point out mistake i've made ?
i think problem here
do{ scanf("%d",&c[i]); i++; }while(c[i]!=0);
consider current value of i
0
, entering value @ c[0]
after increamenting value of i
. i
become 1
, checking c[1] != 0
problem
use
i=-1; do{ i++; scanf("%d",&c[i]); }while(c[i]!=0);
Comments
Post a Comment