Reputation: 1190
I'm trying to print all characters stored in hex array to the screen, one by one, but I get this strange error in line 16. As far as I know, %c should be expecting a char, not an int. Why I'm getting this error? Below is my code, thanks.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>
int main()
{
char hex[8] = "cf0a441f";
int hexCounter;
char *currentHex;
for(hexCounter=0; hexCounter<strlen(hex); hexCounter++)
{
currentHex = &hex[hexCounter];
printf("%c",currentHex);
}
return 0;
}
Upvotes: 3
Views: 25707
Reputation: 33
Here's the modified code which runs fine for me -
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>
int main()
{
char hex[9] = "cf0a441f";
unsigned int hexCounter;
char *currentHex;
for(hexCounter=0; hexCounter<strlen(hex); hexCounter++)
{
currentHex = &hex[hexCounter];
printf("%c",*currentHex);
}
return 0;
}
Upvotes: 0
Reputation: 17356
You have hex[hexCounter]
as a char
so when you set
currentHex = &hex[hexCounter];
you are setting currentHex
to the address of a char
, i.e. a char *
. As such, in your printf
you need
printf("%c",*currentHex);
What you are doing is unnecessary anyway, since you could just do
printf("%c",hex[hexCounter]);
Upvotes: 2
Reputation: 16718
currentHex
should be of type char
, not char *
.
char currentHex;
[..]
currentHex = hex[hexCounter];
printf("%c",currentHex);
If you really want it to be a pointer, dereference it to print:
printf("%c",*currentHex);
Upvotes: 0
Reputation: 399803
You mean
printf("%c", *currentHex);
In my opinion you can remove the entire idea of currentHex
since it just adds complexity for no value. Simply do:
printf("%c", hex[hexCounter]);
The important point is that you're supposed to pass the value of the character itself, not it's address which is what you're doing.
Upvotes: 8