Connecting Tech Pros Worldwide Help | Site Map

char array to int array

rajus
Guest
 
Posts: n/a
#1: Mar 11 '06
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
Guest
 
Posts: n/a
#2: Mar 11 '06

re: char array to int array


rajus schrieb:[color=blue]
> 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.[/color]

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
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Neil
Guest
 
Posts: n/a
#3: Mar 12 '06

re: char array to int array


rajus wrote:[color=blue]
> 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.
>[/color]
a loop and atoi()
Jim Smith
Guest
 
Posts: n/a
#4: Mar 12 '06

re: char array to int array


Neil <NeilKurzm@worldnet.att.net> writes:
[color=blue]
> rajus wrote:[color=green]
>> 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.
>>[/color]
> a loop and atoi()[/color]

No.
rajus
Guest
 
Posts: n/a
#5: Mar 12 '06

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
Guest
 
Posts: n/a
#6: Mar 12 '06

re: char array to int array


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

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

--
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.
Closed Thread