I have this code and it works perfectly fine except when my input is the number "2" .
I don't know why, the code seems ok... Is there something wrong?
void initValue(int *a, int dim, int value, int i);
int findValue(int *a, int dim, int value, int i);
main(){
int i, value, dim = 5;
int a[dim];
initValue(a, dim, value, i);
printf("\nYour values are: ");
for(i = 0; i < dim; i++) printf("%d ", a[i]);
printf("\n\n");
}
void initValue(int *a, int dim, int value, int i){
printf("Insert your values:\n");
for(i = 0; i < dim; i++){
scanf("%d", &value);
if(findValue(a, dim, value, i) == 1){
printf("This value already exist, please insert a new one.\n");
i--;
}
else a[i] = value;
}
}
int findValue(int *a, int dim, int value, int i){
int j, result = 0;
for(j = 0; j < i || a[j] != value; j++) if(a[j] == value) result = 1;
return result;
}
You have to check that scanf()
did succeed, something like
if (scanf("%d", &value) != 1) maybeRemoveAllWhitespacesAndScanfAgain_MaybeReturnWithAnError();
You decrement i
and never check if i < 0
for(i = 0; (i < dim) && (i >= 0) ; i++){
initValue()
could be defined as
void initValue(int *a, int dim) { int value; int i; . . . }
there is no point in passing the variables from main()
.
One more thing, if you initialize value
before scanf()
you can prevent trying to access it while uninitialized.
The error in your code is a logic error in this line:
for(j = 0; j < i || a[j] != value; j++) if(a[j] == value) result = 1;
Say you have dim=5
and i=2
and value=10
, which is not there is a
. The loop will not stop at j=2
because a[j] != value
is true. After that you are entering undefined behavior territory.
That line needs to be changed to:
for(j = 0; j < i ; j++) if(a[j] == value) return 1;
The function can now be simplified to:
int findValue(int *a, int dim, int value, int i){
int j = 0;
for(j = 0; j < i ; j++)
{
if(a[j] == value)
{
result = 1;
}
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.