I'm trying to print the ascii value (ascii int numbers) of a char*
for example A
as 65 as on the ascii table.
Here is the code I have.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int i = 0;
printf(" Hello World \n");
printf("argv[0] is %s! \n",argv[0]);
printf("argv[1] is %s! \n",argv[1]);
printf("argv[2] is %s! \n",argv[2]);
printf("argv[3] is %s! \n",argv[3]);
if( argc == 4 )
{
printf("The first argument supplied is %s\n", argv[1]);
printf("The second argument supplied is %s\n", argv[2]);
printf("The third argument supplied is %s\n", argv[3]);
}
else if( argc > 4 )
{
printf("Too many arguments supplied.\n");
exit( 1 );
}
else
{
printf("Not enough arguments supplied. \n");
exit( 1 );
}
for(i = 1; i < 100; i++)
{
printf("i is %d argv[i] %d\n", i, argv[i]);
}
return(0);
}
I want these values to be entered from the command so this is what I put in.
./a.out A B C
When I compile it I get this warning.
warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘char *’
If I cast the argv[i]
to (int)
I get this message.
warning: cast from pointer to integer of different size
If I cast the argv[i]
to (int *)
I get this message.
warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int *’
is the problem causing line. Using incorrect format specifier is undefined behaviour in C.
argv
is of typechar**
but%d
format specifier expects anint
. So to print the ascii values of arguments, you'll need a nested loop overargv
.Note that your loop condition is not correct. You only have
strlen(argv[j])
characters for each argument. So you can't arbitrarily print for100
chars.Move these printf statements
below the arguments checking so that you would only print them after arguments checking. Otherwise, you might end up accessing arguments that are not there if fewer arguments are passed.