I’m trying to build a function that takes 1 param: the number as char[] and returns a char** with the divisors as strings.
I have come up with the following function, which works only for some numbers.
char** calc_div(char nr[100])
{
int nri,i,ct=0;
char **a = (char**)malloc(sizeof(char*));
nri = atoi(nr);
for(i=0;i<sizeof(char*);i++)
a[i] = (char*)malloc(sizeof(char));
for(i=1;i<=nri;i++)
if(nri % i == 0)
{
sprintf(a[ct++],"%d",i);
}
return a;
}
This works for numbers like 22, 33, 77 but not for 66 or 88 (it just gets stuck somewhere). Could anyone help me?
So many problems in such a small space…oh dear!
Let’s think about the interface first…how does the calling code know how many values are returned? Presumably, there must be a null pointer at the end of the array of pointers. Also, for each number bigger than 1, we know that 1 and the number itself will be divisors, so we are going to need an array of at least 3 pointers returned. If a number is not prime or one, then there will be more values to push into the array. Therefore, one of the things we’ll need to do is keep tabs on how many values are in the array. Also, the memory release code will need to step through the returned array, releasing each string before releasing the array overall.
So, we get some ideas about what the code should do. How does your code fare against this?
This allocates one entry in the return array. We now know we need at least 3 times as much space, and we also have to keep a record of how much space was allocated.
This allocates 4 or 8 strings of size 1 byte each, assigning them to successive elements of the array of size 1 previously allocated. This is a guaranteed buffer overflow on the array
a. Plus, because the strings are only big enough to hold the null at the end of string, you can’t put any answers in there. You should probably be allocatingstrlen(nr)+1bytes sincenris one of the numbers you’ll need. It is not remotely clear that numbers are limited to either 3 or 7 factors (since you also need to allow for the terminating null pointer).The code inside the body of the
ifstatement will have to be ready to do memory allocation for the new factor and for the array as and when necessary.