Home > Blockchain >  How can I solve the error getting by using array in condition
How can I solve the error getting by using array in condition

Time:12-04

I want to make a program which will sperate integer values given by user and then will store on odd.txt and even.txt

It will take inputs of number from user and store them in num[] array. And therefore after checking the numbers it will post in on sperate files

Here is code --

#include <stdio.h>

#include <string.h>

int main(int argc, char * argv[]) {
  FILE * odd;
  FILE * even;

  odd = fopen("odd.txt", "w");
  even = fopen("even.txt", "w");

  int range;

  printf("Enter range : ");
  scanf("%d", & range);
  int * num[range];

  for (int i = 0; i <= range; i  ) {
    printf("Enter number %d : ", i   1);
    scanf("%d", & num[i]);
  }

  for (int i = 0; i <= range; i  ) {
    if (num[i] % 2 == 0) {
      fprintf(even, "%d\n", num[i]);
    } else {
      fprintf(odd, "%d\n", num[i]);
    }
  }
}
```



 but getting error here --

if (num[i] % 2 == 0)

Error : Invalid operands to binary expression ('int*' and 'int')

CodePudding user response:

The error message you're seeing is because you are trying to use the modulo operator (%) on an int * value, which is not allowed. This is happening because you have declared the num array as an array of int * values, instead of an array of int values.

To fix this error, you should change the declaration of the num array to use int values instead of int * values. For example, you could change the declaration of the num array to the following:

int num[range];

With this change, the num array will be an array of int values, and you will be able to use the modulo operator on its elements without getting the error you're seeing.

Additionally, you should also make sure that you are using the correct syntax for accessing elements of the num array. Currently, you are using the & operator when you read values from the num array, but this is not necessary because num is already an array of int values. Instead, you should just use the array subscript operator ([]) to access elements of the num array, like this:

scanf("%d", &num[i]);

You should also use the array subscript operator when you access elements of the num array in the second for loop, like this:

if (num[i] % 2 == 0)

With these changes, your code should work as expected and you should not see the error you're currently seeing.

  • Related