I am trying to find the multiple of two numbers supplied as arguments in the command line using the following code:
#include <stdio.h>
/**
* main - Entry point for my program
* @argc: This is the number of arguments
* @argv: This is the array of arguments
*
* Return: Zero upon program success
*/
int main(int argc, char *argv[])
{
int i;
int result = 1;
for (i = 1; i < argc; i++)
{
result = result * argv[i];
}
printf("%d\n", result);
return (0);
}
But as I try to compile my code, I get the following error:
3-mul.c: In function ‘main’:
3-mul.c:19:19: error: invalid operands to binary * (have ‘int’ and ‘char *’)
19 | result = result * argv[i];
| ^ ~~~~~~~
| |
| char *
How do I get around this error?
The line
will not work, because
argv[i]is not an integer, but it is of typechar *, i.e. a pointer to a string. It does not make sense to multiply an integer with a pointer.What you want to do is to convert the string pointed to by
argv[1]to an integer, and then multiply that integer withresult. A simple way to do this would be to use the standard library functionstrtol, by changing the lineto
and by adding
#include <stdlib.h>to the start of the file.If the conversion fails, then the function
strtolwill simply return0, causing your final result to also be0. Also, if the user enters a number that is so large that it is not representable as along, then the functionstrtolwill simply return the largest representable number. If that is not what you want, then you probably want to print an error message instead:For the command-line arguments
this program has the following output:
For the command-line arguments
this program has the following output:
For the command-line arguments
this program has the following output:
For the command-line arguments
this program has the following output:
This program is still not perfect, though, because, as shown above, it is accepting the command-line argument
5abcas a valid representation for the number5. If you want that argument to be rejected too, then the program would have to perform further validation tests.