I’m new to C and I’m having a small problem with my code:
int i, n;
int *arr;
while(n != 0) {
scanf("%d", &n);
if(n == 0)
exit(1);
else {
arr = (int*) malloc(sizeof(int) * n);
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);
} //end if
} //end while
What I’m trying to do is to make an array of n size and I want to stop reading when I get a ‘0’ for example if I enter:
3
2
2
5
2
6
7
0
I want an array of size 3 with values 2, 2, 5, an array of 2 with values 6 and 7 and exit because of the 0
* Sorry, I left out an important part I think… In my code a call a calc() where I send arr, right after scanf(“%d”,&arr[i]) and then i’ll return the value and then if the next values e.g. 2 isn’t 0 I’ll read, create a new array, send arr, print result on console and again if the next value is 0 then it will exit. *
Could you guys tell me where I’m wrong?
The problems which are visible in your code are:
1. Checking uninitialized integer
ninwhile. To fix this either initializento non zero or use ado{ ... } while()instead ofwhile().2. You need to validate the value of
nwhich is read throughscanf.malloctakessize_ttype as the parameter which isunsigned int. Butnbeing an integer can accept negative values, thus if a negative value is entered it will be passed asunsigned inttomalloc, this may lead to undesired results (Alsoforloop will be executed incorrect number of times). You may also consider changing the type ofnfromintegertounsigned inttype or change the exit condition toif( n < 1 ).3. There is memory leak in your program. Memory allocated through
mallocis not freed throughfree.4. Do not assume that
mallocwill always succeed. Please check for the success ofmallocthrough aNULLcheck i.e.5.
exitwith non zero value generally indicates abnormal termination. You can usebreakorreturn.breakmight be a better idea as it generally gets difficult to test a function as the exit points in the function increase (though this may not be true in your case, but it is FYI)6. Optionally, you can check the return value of
scanfto make sure that a valid input was entered.Help this helps!