The first thing I notice all the warnings that your code generates (such as passing an int* to a size_t* parameter, which is a no-no). I would change all of your size_t's to int's as there is really no point to using size_t here. _itoa is a non-standard function. What compiler are you using?
This
Code:
if (d_len - temp_len == 0)
is more commonly written as
Code:
if (d_len == temp_len)
Here's something strange:
Code:
while (d > 0)
{
int d_split = d % 10;
splited[i] = d_split;
break;
}
That's the same as saying this (i.e., there isn't really a loop because of the break):
Code:
splited[i] = d % 10;
Is splitDigit divided into two parts just to ensure that any unused elements of the split array are 0? Then just use calloc to ensure they are zero from the start.
The function would be more generally useful if it accepted a string and returned the check digit.
Also, main returns int, not void (void is non-standard although allowed by some compilers). And you don't need the backslash at the end of line 73. Literal strings separated by only whitespace are concatenated (and a newline is whitespace).
So, putting some of this into your code yields:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GROUP_SIZE 5
/* (Not needed anymore.)
char* intToCharArray(int n) {
int sz = snprintf(NULL, 0, "%d", n); // how much space is needed?
char *str = malloc(sz + 1); // +1 for null char
sprintf(str, "%d", n);
return str;
}
*/
int* splitDigit(int d, int d_len) {
int* split = calloc(d_len, sizeof *split);
for (int i = d_len - 1; i >= 0; i--) {
split[i] = d % 10;
d /= 10;
}
return split;
}
int oddEvenSum(int* arr, int arr_len, int start, int increment) {
int sum = 0;
for (int i = start; i < arr_len; i += increment)
sum += arr[i];
return sum;
}
int calcUpcCheckDigit(const char *upc) {
int zth, first, second;
sscanf(upc, "%1d %d %d", &zth, &first, &second);
int* firstSplit = splitDigit(first, GROUP_SIZE);
int* secondSplit = splitDigit(second, GROUP_SIZE);
int temp[11] = {zth};
for (int i = 1; i < 11; i++) {
if (i < 6) temp[i] = firstSplit[i - 1];
else temp[i] = secondSplit[i - 6];
}
free(firstSplit);
free(secondSplit);
return 9 - ( (oddEvenSum(temp, 11, 0, 2) * 3
+ oddEvenSum(temp, 11, 1, 2) ) - 1) % 10;
}
int main() {
char line[100];
printf("Enter the 11 digit UPC code in the following format\n"\
"*** 0 12345 67890 ***\n>>> ");
fgets(line, sizeof line, stdin);
int check_digit = calcUpcCheckDigit(line);
printf("Check digit is: %d\n", check_digit);
}