我是一個初學者,我做了一些練習,學習C.Ç - 的malloc與結構的循環與指針
我的工作與結構和指針的動態內存分配。我有這樣的結構:
struct fact_entry
{ /* Definition of each table entry */
int n;
long long int lli_fact; /* 64-bit integer */
char *str_fact;
};
這是我的主要代碼:
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;
}
的想法是,以填補20行的陣列。然後每行有3列。在第一列中,它顯示了行「i」的數字,第二行顯示了行數的階乘,第三行與第二行相同,但是是字符串格式。
我使用log10來知道字符串有多長。
程序的執行顯示了這個:
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
線0應該在第三列顯示1,會發生什麼?它出現了malloc錯誤。
謝謝!
未定義的行爲!=「即時保證崩潰」。 (如果只有它!) – 2014-10-27 21:10:41
次要的東西:'sizeof(char)'是1,總是。這是因爲'sizeof(char)'是用於測量C中大小的*單位*;它不可能是其他任何東西(即使你使用的是非常奇怪的硬件,例如15位字節)。所以當分配'char'緩衝區時,你永遠不需要'sizeof'。 – Leushenko 2014-10-27 21:14:36
感謝Leushenko,然後我明白,而不是sizeof(字符)我可以直接把變量p,包含數字的字符數。 – 2014-10-27 21:22:35