char array to int array

R

rajus

How to convert a char array to an int array?So if

char s[]={"1234"};
then the int array say 'num' should have values num[0]= 1 num[1]=2 and
so on.
 
M

Michael Mair

rajus said:
How to convert a char array to an int array?So if

char s[]={"1234"};
then the int array say 'num' should have values num[0]= 1 num[1]=2 and
so on.

Allocate sufficient storage, say with
int *array = malloc(strlen(s) * sizeof *array);
if (array == NULL) {
/* Your error handling here; in its absence: */
exit(EXIT_FAILURE);
}
Then iterate through s, make sure that you have a digit,
e.g. by using isdigit(); if you find a non-digit, terminate,
if the non-digit is not '\0', emit an error message;
whenever you have a digit, convert this digit to the
digit's value (e.g. using "digit - '0'") and store it in
the appropriate element of array.

If your implementation does not work, post your compiling
code here and explain your problem as clear as possible.

Cheers
Michael
 
N

Neil

rajus said:
How to convert a char array to an int array?So if

char s[]={"1234"};
then the int array say 'num' should have values num[0]= 1 num[1]=2 and
so on.
a loop and atoi()
 
R

rajus

Thanks! The digit-' 0' is a great way to convert the char to int and
also the dynamic allocation.
Thanks.
 
K

Keith Thompson

rajus said:
Thanks! The digit-' 0' is a great way to convert the char to int and
also the dynamic allocation.
Thanks.

Please read <http://cfaj.freeshell.org/google/>.

I'm not sure whether this has been mentioned in this thread, but the
digit-'0' trick is guaranteed to work because the C standard requires
the digit characters '0' through '9' to be consecutive and ordered.
Keep in mind that there is no such guarantee for letters (and there
are character sets in use where the letters are not consecutive).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top