Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   char array to int array (http://www.velocityreviews.com/forums/t441740-char-array-to-int-array.html)

 rajus 03-11-2006 05:39 PM

char array to int array

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.

 Michael Mair 03-11-2006 06:25 PM

Re: char array to int array

rajus schrieb:
> 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.

code here and explain your problem as clear as possible.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.

 Neil 03-12-2006 04:05 AM

Re: char array to int array

rajus wrote:
> 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()

 Jim Smith 03-12-2006 04:34 AM

Re: char array to int array

Neil <NeilKurzm@worldnet.att.net> writes:

> rajus wrote:
>> 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()

No.

 rajus 03-12-2006 03:20 PM

Re: char array to int array

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

 Keith Thompson 03-12-2006 08:53 PM

Re: char array to int array

"rajus" <rajas3@gmail.com> writes:
> Thanks! The digit-' 0' is a great way to convert the char to int and
> also the dynamic allocation.
> Thanks.

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).

--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.

 All times are GMT. The time now is 12:39 PM.