Reputation: 5
I'm trying to compare two equal arrays, using a for loop and an if statement to see if the values aren't equal. They shouldn't be, but it's running my code after the if anyway.
#include <stdio.h>
bool arrayChecker(int a[10], int b[10]);
int main ()
{
bool output;
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int b[10] = {1,2,3,4,5,6,7,8,9,10};
output = arrayChecker(&a[10], &b[10]);
printf("%d", output);
return 0;
}
bool arrayChecker(int a[10], int b[10]){
bool result = true;
for(int i = 0;i<10;i++){
if(a[i] != b[i]){
result = false;
printf("this is being printed and shouldn't be'\n");
}
}
return result;
}
Upvotes: 0
Views: 61
Reputation: 498
1st change: means that the arrayChecker
gets two pointers to some memory segment (in this case your arrays).
2nd change can be written also as output = arrayChecker(&a[0], &b[0]);
because with using &a[0]
you send to your function a reference to the first element of your array. array elements are arranged sequentially one after other in the memory so there is no problem to iterate from the first one (a[0]
).
#include <stdio.h>
bool arrayChecker(int *a, int *b); //first change here
int main ()
{
bool output;
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int b[10] = {1,2,3,4,5,6,7,8,9,10};
output = arrayChecker(a, b); //second change here
printf("%d", output);
return 0;
}
bool arrayChecker(int *a, int *b) {
bool result = true;
for(int i = 0;i<10;i++){
if(a[i] != b[i]){
result = false;
printf("this is being printed and shouldn't be'\n");
}
}
return result;
}
Upvotes: 0
Reputation: 1485
You are passing the wrong thing to the arrayChecker function.
You should have:
output = arrayChecker(&a[0], &b[0]);
or
output = arrayChecker(a, b);
What you are passing is the address of the memory location right after the end of the arrays, and comparing the 10 ints after that, which hold random values as far as your program is concerned.
Upvotes: 3