I'm a beginner and I'm doing some exercises to learn C.
I'm working on dynamic memory allocation with structs and pointers. I have this struct:
struct fact_entry
{ /* Definition of each table entry */
int n;
long long int lli_fact; /* 64-bit integer */
char *str_fact;
};
And this is my main code:
int
main (int argc, char *argv[])
{
int n;
int i;
struct fact_entry *fact_table;
if (argc != 2)
panic ("wrong parameters");
n = atoi (argv[1]);
if (n < 0)
panic ("n too small");
if (n > LIMIT)
panic ("n too big");
/* Your code starts here */
int p;
fact_table = (struct fact_entry *)malloc(n*sizeof(struct fact_entry));
if(fact_table==NULL)
{
fprintf(stderr, "Out of memory, exiting\n");
exit(1);
}
for (i = 0; i<= n; i++)
{
fact_table[i].n = i;
p = i;
fact_table[i].lli_fact=1;
while(p>0)
{
fact_table[i].lli_fact = p * fact_table[i].lli_fact;
p--;
}
p = (int)log10(fact_table[i].lli_fact)+1;
fact_table[i].str_fact = malloc(p);
if(fact_table->str_fact==NULL)
{
fprintf(stderr, "Out of memory, exiting\n");
exit(1);
}
sprintf(fact_table[i].str_fact,"%lld",fact_table[i].lli_fact);
}
/* Your code ends here */
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 idea is to fill an array of 20 rows. Then every row have 3 columns. In the first column it shows the number of the line "i", in the second, the factorial of the number of the line, in the third the same that in the second but in string format.
I use the log10 to know how long will be the string.
The execution of the program shows this:
0 1 |g�!�2�
1 1 1
2 2 2
3 6 6
4 24 24
5 120 120
6 720 720
7 5040 5040
8 40320 40320
9 362880 362880
10 3628800 3628800
11 39916800 39916800
12 479001600 479001600
13 6227020800 6227020800
14 87178291200 87178291200
15 1307674368000 1307674368000
16 20922789888000 20922789888000
17 355687428096000 355687428096000
18 6402373705728000 6402373705728000
19 121645100408832000 121645100408832000
20 2432902008176640000 2432902008176640000
Line 0 should show 1 in the third column, what happens? It Appears somthing wrong with the malloc.
Thanks!
sizeof(char)is 1, always. That's becausesizeof(char)is the unit used to measure sizes in C; it's impossible for it to be anything else (even if you're on really weird hardware with e.g. 15-bit bytes). So when allocatingcharbuffers, you never needsizeof.