Hi, I have the below code:
Code:
struct fact_entry
{
int n;
long long int lli_fact;
char *str_fact;
};
int main (int argc, char *argv[])
{
int n;
int i;
struct fact_entry *fact_table;
n = atoi (argv[1]);
fact_table = (struct fact_entry *)malloc(n*sizeof(fact_table));
for (i=0; i<n; i++) {
if(i==0) {
fact_table[i].n = 0;
fact_table[i].lli_fact = 1;
fact_table[i].str_fact = "1";
}
else {
fact_table[i].n = i;
fact_table[i].lli_fact = i*fact_table[i-1].lli_fact;
/* the next line seems to be wrong*/
fact_table[i].str_fact = (char *)malloc(log10(fact_table[i].lli_fact));
}
}
for (i=0; i<n; i++) {
printf("%d %lld %s\n", fact_table[i].n, fact_table[i].lli_fact, fact_table[i].str_fact);
}
return 0;
}
The program accepts an integer and return 3 columns, the 1st column is the array position, the 2nd column is the factorial and the 3d column is also the factorial but in string format.
The 2 first columns are fine, it's the 3rd column that's failing, so I'm allocating memory the wrong way for the string within the struct. Could someone let me know what I'm doing wrong?
Regards