Reputation: 558
I am trying get number ASCII for letter in char variable. My code so far is:
int main (int argc,char* argv[]) {
char c="A"; //here error
char b="'"; //here error
char d="z"; //and here error
printf("%d\n %d\n %d\n",c,b,d);
}
But I get the following errors:
analizer.c: In function ‘main’: analizer.c:13:8: warning: initialization makes integer from pointer without a cast [enabled by default] analizer.c:14:8: warning: initialization makes integer from pointer without a cast [enabled by default] analizer.c:15:8: warning: initialization makes integer from pointer without a cast [enabled by default]
Upvotes: 2
Views: 1958
Reputation: 505
In C
strings are just an array of characters which terminate with a \0
. So if you want to use only one character, declare a char
variable and use the character single
quote. If you want to use a string, declare char
array and use double
quote as
char a='A' // just one character
char b[20]="Some_Text"// multiple characters(a string)
In the first case, a
contains the integer value of 'A' but in the second, b
contains the base address of the string it points to. Each character in array b[]
must be accessed with indexes as b[0]
b[1]
etc.
You can use strings to represent single characters as
char a[]="A" // a string of size 1
and then you can print it's integer equivalent as
printf("%d",a[0]); //0th element of the string
use the single quote method as described in other answers.
Upvotes: 1
Reputation: 75062
"A"
is a string literal (an array of characters). 'A'
is a character constant (an integer). What you want should be latter.
#include <stdio.h>
int main (int argc,char* argv[]) {
char c='A';
char b='\''; // use escape sequence
char d='z';
printf("%d\n %d\n %d\n",c,b,d);
}
The compiler will allow you to extract elements of the arrays (string literals) like below, but using character constants should be better in this case.
#include <stdio.h>
int main (int argc,char* argv[]) {
char c="A"[0]; // a typical way to deal with arrays
char b=*"'"; // dereferencing of a pointer converted from an array
char d=0["z"]; // a tricky way: this is equivalent to *((0) + ("z"))
printf("%d\n %d\n %d\n",c,b,d);
}
Upvotes: 6
Reputation: 1518
Basically you point to a string literal when you do this (which is invalid):
char c="A";
You need to write a single char to the variables:
char c='A';
char b='\'';
char b='z';
Upvotes: 2