tags:

views:

90

answers:

4

Is it possible to retrieve an integer using scanf and assigning each digit to a int array?

I'm trying to achieve it doing it this way:

int numbers[];
puts("Enter number");
int x;
scanf("%d",x);
numbers = malloc(x);
numbers = x;
A: 

You can just read it in as a string %s into a char array.

At that point you have each digit in a char.

A char is just an int value. So you can apply any transformation after that to the character that you read in.

You can convert each char digit to its int value and you could then iterate over each char in the string and do something like this:

myInts[i] = charBuffer[i] - '0'; /* where i = 0.. string length -1 */
Brian R. Bondy
@Brian: My guess is one of OP's problem is to determine the amount of memory to allocate.
Moron
A: 

Not magically like that, you would need to read in the int and break up the digits yourself, or read it as a string so you can access each character individually

Michael Mrozek
A: 

Everyone else has pretty good answers to what you want, just want to point out what your code is really doing---

numbers = malloc(x);

Here you've read in the user's input and allocated an array of x bytes on the heap. Numbers points to that memory. It's your only way to get to that array.

numbers = x;

Then you've assigned numbers to the integer x. You've now lost track of the memory allocated by malloc and have no way to delete it using free().

Doug T.
+1  A: 

Two quick tricks :

Integer to string :

int N;
char buf[10];
scanf("%d",&N);
sprintf(buf,"%d",N);

Integer to array:

int N,i,
    buf[10],
    Dig;
scanf("%d",&N);
Dig = log10(N);
for(i = Dig; N ; i--){
   buf[i] = N % 10;
   N /= 10;
}
Debanjan