-1

Background

Im trying to determine character codes for some national diactric letters.

Problem

Is something is wrong with my code?

char a = "a"; // "a" ascii code is 97

char buffer[8];

itoa(buffer,(int)a, 10);

print(buffer); // but it prints "252" instead of "97"
Kamil
  • 13,363
  • 24
  • 88
  • 183

3 Answers3

3

The character code for 'a' is indeed 97, but "a" is of type char *. Single quotes ' encode characters, double quotes " encode string literals.

Try

char a = 'a';
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • It worked, code is fine, but now I have another problem with diactric. I will create another thread/question. – Kamil May 12 '14 at 08:21
2
char a = "a";

The problem is that "a" is a C string, a pointer to null-terminated array of char. This means that you end up assigning some part of an address rather than the ordinal value of a character.

You need to assign a char like this:

char a = 'a';

If you compiled with warnings enabled then the compiler would have told you about the mistake. For instance, my GCC compiler, with -Wall says:

main.c: In function 'main':
main.c:3:14: warning: initialization makes integer from pointer without a cast [enabled by default]
     char a = "a"; // "a" ascii code is 97
              ^

You must also never write:

printf(buffer);

If buffer contains any format strings, then this will lead to printf attempting to read parameters that you did not supply.

Instead write

printf("%s", buffer);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

You are assigning a char* to char at the line:

char a = "a"; // "a" ascii code is 97

Don't you have a compiler error or warning?

Also since you are trying to determine the character encoding you have to make sure your source file is encode correctly (UTF8, ANSI...)

mathk
  • 7,973
  • 6
  • 45
  • 74