Unspecified return from a function
An answer to this question on Stack Overflow.
Question
I've been teaching myself C through various sources. One of exercises I've found is this past year's cs50 problem sets ([found here][1] under the heading Bad Credit). Essentially, I've solved the problem but realized that I am performing the same step twice and perhaps could wrap that step inside of a function to be reused.
My problem is that I'm not sure how to define a return to an as yet unspecified array. Or, for that matter, if this is a good idea. I think that reusing the code would be a good thing if I could make it work, but I can't figure out how to do so.
The problem, as shown in the code below is taking a long number, separating each individual digit, and performing a bit of math to do a checksum. This is returned to step1 in the code below. The do/while loop is doing the heavy lifting here, and what I would like to do is to do the same with elements in step1 and return those into step2 or any other variable for that matter.
long long num = 378282246310005;
int step1[10];
int step2[10];
do {
int i = 0;
step1[i] = num % 10; // this returns to one array
num /= 10;
i++;
} while (num != 0);
I realize this isn't that big a deal for this problem. I just decided that it would be good to know how to do it, if possible. [1]: http://cdn.cs50.net/2012/fall/psets/1/hacker1.pdf#page=10
Answer
You can pass the array by reference, like so:
//Number to checksum is num
//Array to store checksum is arr
//Maximal length of arr is n
void checksum(long long num, int arr[], int n){
int i = 0;
do {
arr[i] = num % 10; // this returns to one array
num /= 10;
i++;
if(i==n) return; //break before we overflow array
} while (num != 0);
}
Note that your code is potentially unsafe because you may end up writing to a part of the array beyond the memory you've allocated for it. That is, you define int step1[10] but may end up writing to step[11].
Also, you stuck your int i=0 inside of the loop. I assumed you wanted it outside.