Working on a exercise out and I would like a little help with one part of my code.. Not really looking for people to solve the exercise for me.
Using a function to turn an int - into a array for futher processing.
What I think needs to happen is (guessing and checking here) is call the length
of the dynamic array as a pointer, as the function I am using is already returning an array? And I thought arrays could not return via functions, so I am feeling a little confused here. I guess if some one could fill in my comments in my code, with valid code It would help me understand what is happening here.
#include <iostream>
#include <math.h>
char * convertNumberIntoArray(unsignedint number);
usingnamespace std;
int main(int argc, constchar * argv[])
{
int digit;
cout << "Please enter in a digit: ";
cin >> digit;
cout << endl;
convertNumberIntoArray(digit);
// I would like to get the arr back into main
// and do somthing like this...
// for (int i = 0; i < arr.length; i++) {
// # Do stuff..
// }
return 0;
}
char * convertNumberIntoArray(unsignedint number) {
int length = (int)floor(log10((float)number)) + 1;
char * arr = newchar[length];
int i = 0;
do {
arr[i] = number % 10;
number /= 10;
i++;
} while (number != 0);
return arr;
}
Indeed, a function cannot return an array, however, it can return a pointer to one.
convertNumberIntoArray returns a pointer to a character, namely, the first element of the array it allocates.
In main, you call convertNumberIntoArray, but don't store its return value. Do something like this:
char* arr = convertNumberIntoArray(digit);
Sadly, a pointer to an array and an array are two different animals: you cannot determine the length of a dynamically allocated array; you're going to have to calculate it manually or deduce it logically.
If you have no need for a character array, then don't use one; change your function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int* convertNumberIntoArray(int number)
{
int length = (int)floor(log10((float)number)) + 1;
int* arr = newint[length];
int i = 0;
for (int i = 0; number != 0; ++i)
{
arr[i] = number % 10;
number /= 10;
}
return arr;
}
Wow. Thank you for pointing that out. That is the trouble with using other peoples code, that I don't fully understand. (have not arrived at dynamic arrays yet - In my studying - working through conditional programs currently. So I am getting ahead of my self a bit. )