I need to convert an array element (char type) to a int variable.Need to know how i cast it.language is c. If any one have an idea about this please send me a reply. <email address removed per Posting Guidlines>
Convert array element
Collapse
X
-
-
Hi,
Try defining the array variable as type void, then typecast it to the different types.
ex.
#include <stdio.h>
#include <stdlib.h>
int main(){
void *x = NULL;
x = (int *)1;
printf("the value is %d\n",(int *)x);
x = (char *)'A';
printf("the character is %c\n",(char*)x) ;
}
result:
the value is 1
the character is A
Hope this helped.
Desmond -
Remember code tags:
Could you perhaps explain what happens atCode:#include <stdio.h> #include <stdlib.h> int main(){ void *x = NULL; x = (int *)1; printf("the value is %d\n",(int *)x); x = (char *)'A'; printf("the character is %c\n",(char*)x); }
Why are you using that?Code:void *x = NULL;
I'm a C++ girl so I'm just wondering ;-)Comment
-
character variables are stored in C as byte sized integers so there is no need to cast between the typesOriginally posted by samitha1010I need to convert an array element (char type) to a int variable.Need to know how i cast it.language is c. If any one have an idea about this please send me a reply. <email address removed per Posting Guidlines>
e.g. consider this fragment of code when contains an array of char, the elements of which are printed as character using %c and decimal integer using %d
when run givesCode:char ch[]={'A','B','C'}; int i; for(i=0; i<3;i++) printf("character %c integer value %d\n", ch[i], ch[i]);
character A integer value 65
character B integer value 66
character C integer value 67
the ASCII character code for A is 65 decimalComment
-
hi,
You said in you initial statement that the language is c. I assumed you wanted c version.
Anyway, it does not matter. "void *" takes anything. This allows you to store and retrieve any data type that you want by type casting it when storing, retrieving, allocating,and distroying the memory area. "void *" gives you more control of you datatypes.
It also works perfectly in c++. I am also a c++ developer.
There are also other ways.
desmond.Comment
Comment