C easy code with filling array -
i'm trying fill array file called data.txt
. don't know what's wrong code. segmentation fault: 11 error.
#include <stdio.h> #include <stdlib.h> void input(int arr[]){ file* f; int x, i=0; f= fopen("data.txt","r"); while (arr[i] != eof){ fscanf(f,"%d",&x); arr[i] = x; i++; } fclose(f); } int main(){ int arr[50]; input(&arr[50]); printf("%d", arr[0]); }
you reading number x
(which copying arr[i]
) , comparing arr[i+1]
eof
. not how has done.
try this
while (fscanf(f, "%d", &arr[i]) == 1) i++;
but violate many safety constraints. better bound check , break if i
greater limit, limit should passed function.
another error how passing arguments input. pass input(arr)
instead of input(&arr[50])
. if want use &
use input(&arr[0])
.
Comments
Post a Comment