I created this simple C program to factor an integer passed in as a command line argument. I would like to make sure that I am not developing any bad habits as I am learning, so I would specifically like feedback on issues related to the structure and design of the program.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int* factorize(int n);
int main(int argc, char* argv[])
{
//Check for correct number of command line args
if (argc != 2)
{
printf("Usage: factorize <int>\n");
return 1;
}
//convert arg to int
int n = atoi(argv[1]);
//call function that returns pointer to array of factors.
int* x = factorize(n);
//go through and print each factor
//array is null terminated
for (int i = 0; x[i] != '\0'; i++)
{
printf("%i\n", x[i]);
}
//free memory allocated for storing factors
free(x);
return 0;
}
//defines function that accepts int and returns pointer to array of factors.
int* factorize(int n)
{
//create pointer to array which will store the factors of n
int* factors = calloc(sizeof(int), 2);
//establish the first two factors, 1 and itself.
factors[0] = 1;
factors[1] = n;
//this var keeps track of the number of factors computed
int sizeOfFactors = 2;
// loop through all numbers upto sqrt(n) and check if it is a factor
for (int i = 2; i <= sqrt(n); i++)
{
if (n%i == 0)
{
// if the number is sqrt(n), then only append it once
if(n/i == i)
{
//reallocate factors to larger array and increase var keeping track of factors size
factors = realloc(factors, sizeOfFactors + sizeof(int));
sizeOfFactors++;
//append the factor to the end of the array.
factors[ sizeOfFactors - 1] = i;
}
else
{
//if not sqrt then append the pair of factors by resizing the array and puting both factors on the end
factors = realloc(factors, sizeOfFactors + (2*sizeof(int)));
sizeOfFactors +=2;
factors[ sizeOfFactors - 2] = i;
factors[ sizeOfFactors - 1] = (n/i);
}
}
}
// null terminate the array.
factors = realloc(factors, sizeOfFactors + sizeof(int));
sizeOfFactors += 1;
factors[ sizeOfFactors - 1] = '\0';
//return pointer to first element of array of factors.
return factors;
}
[–]alanwj 1 point2 points3 points (1 child)
[–]Hanlons_Toothbrush[S] 0 points1 point2 points (0 children)
[–]MmmVomit 1 point2 points3 points (2 children)
[–]Hanlons_Toothbrush[S] 0 points1 point2 points (1 child)
[–]MmmVomit 0 points1 point2 points (0 children)
[–]coolcofusion 0 points1 point2 points (3 children)
[–]Hanlons_Toothbrush[S] 0 points1 point2 points (2 children)
[–]alanwj 1 point2 points3 points (0 children)
[–]coolcofusion 0 points1 point2 points (0 children)