Question

Every time I try this:

long crypt(int *integer)
{
printf("Enter five digit integer:\n");  
scanf("%i",integer);

int digit1=integer/10000;
int digit2=(integer%10000)/1000;
int digit3=(integer%1000)/100;
int digit4=(integer%100)/10;
int digit5=(integer%10)/1;

const char *digit1c[10];
const char *digit2c[10];
const char *digit3c[10];
const char *digit4c[10];
const char *digit5c[10];

(There's more but this seems to be the problem, I'll add the rest by request.)

then it return this error:

math2.h:44:20: error: invalid operands to binary / (have ‘int *’ and ‘int’)
math2.h:45:21: error: invalid operands to binary % (have ‘int *’ and ‘int’)
math2.h:46:21: error: invalid operands to binary % (have ‘int *’ and ‘int’)
math2.h:47:21: error: invalid operands to binary % (have ‘int *’ and ‘int’)
math2.h:48:21: error: invalid operands to binary % (have ‘int *’ and ‘int’)

I know it has something to do with the operators I used to initialize the digits and I did try changing their type to "int *" but that didn't work. So what's happening here exactly?

Était-ce utile?

La solution

integer is a pointer to int (int*), so when you want to use the int it points to, you need to dereference it:

int digit1=(*integer)/10000; // and so on...

Autres conseils

The parameter integer is not an int object; it's an int* object, i.e., a pointer. (And integer is a misleading name for a pointer object.)

If you change:

int digit1=integer/10000;

to

int digit1 = *integer / 10000;

and make corresponding changes to the rest of your code, it will at least compile. integer is a pointer; *integer is the int object that it points to.

(Also, spaces around binary operators would make your code easier to read. Another good reason to use whitespace is that, if the division were reversed, then this:

int digit1=10000/*integer;

would introduce a /* ... */ comment.)

The issue here is that the type of integer is int *, a pointer which does not support the operators of / and %. There are two solutions to your problem.

  1. Dereference integer, by using the * operator every time you perform arithmatic with it.
    e.g. int digit1=(*integer)/10000;

  2. Change integer to the type int. You have to change the signature of the function, and the scanf will have to be changed to use the & operator, scanf("%i",&integer);

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top