Converting a char array into an int array

• 01-24-2013
Clayton Cuteri
Converting a char array into an int array
I am writing code to multiply two int arrays and in my one function i am trying to convert the char array into an int array. I have tested many parts however i can not find the problem. any help or suggestions would be great!
Code:

```struct integer* convert_integer(char* stringInt){     struct integer *converted = malloc(sizeof(struct integer));     int length, i, *ints;     ints = (int *)malloc(10001 * sizeof(int));     length = strlen(stringInt);     printf("stringInt: %s with length of %d\n", stringInt, length);     converted->size = length;     for(i = 0; i < length; i++)         //printf("stringInt[%d]: %s\n", i, stringInt);         sscanf(stringInt, "%s", ints);         //ints[i] = (int)stringInt[length - i]-'0';         //error with conversion!!!!         printf("ints[%d]: %d\n", i, ints[i]);     converted->digits = ints;     return converted; };```
• 01-24-2013
Clayton Cuteri
struct integer looks like this:
Code:

```struct integer{     int* digits;     int size; };```
• 01-24-2013
dmh2000
if you mean you want to read the argument stringInt character by character and convert each to an integer, you are using sscanf wrong. a %s reads a string, not an integer and it doesn't read a sequence. it just find one string. it would help if you gave an example of what the input looks like.

if your input is like this "1234567" and you want to end up with an array of ints like 1,2,3,4,5,6,7?

if so, then try this
Code:

```for(i=0;i<length;++i) {     ints[i] = stringInt[i] - '0'; }```
if your input is like this "123 456 789..." and you want to end up with an array of ints like this 123,456,789,...
then you will need to tokenize the string one way or the other. sscanf doesn't advance through the input string on its own. so you break the string into tokens and then sscanf(token,"%d",&ints[i]) each one. to tokenize, look up 'strtok'.
• 01-24-2013
0x47617279
Quote:

Originally Posted by Clayton Cuteri
struct integer looks like this:
Code:

```struct integer{     int* digits;     int size; };```

The first "struct integer" is telling the program, that it should expect to get a return in the form of a "struct integer*". Its a function, his not declaring the structure.
• 01-24-2013
Clayton Cuteri
my input reads "12345" and i want to get it to be "54321" (for multiplication reasons). i changed the code to what it looks like in line 11, except for the
Code:

` (int)`
however this did not help...
• 01-25-2013
c99tutorial
Check the indentation in your for loop. Removing the commented-out lines would help. If they are not relevant comments, get rid of them.

Give an example of what your input might be and what the resulting `struct integer' should look like. You said you want to get "54321" but I don't understand because struct integer has two members:

int *digits;
int size;

Presumably digits should point to an array of integers with size items.