崩潰的錯誤在main.c
問題與指針和realloc,用程序用C
#include <stdio.h>
#include "poly.h"
int main (void)
{
struct poly *p0 = polySetCoefficient (polySetCoefficient (polySetCoefficient (polyCreate() , 0, 4.0), 1, -1.0), 10, 2.0);
//polyPrint (p0);
return 0;
}
在poly.c
我剛剛列入,我處理兩種功能,它好像polySetCoefficient
的是,竟然放棄我的人問題。我已經評論了printf語句,但是我使用這些來確定程序崩潰的位置。顯然,它在崩潰之前實際上會經歷整個函數,所以我不確定錯誤是從哪裏來的。其次,在我的main.c文件中,我只調用了兩個函數。另一個問題是,每次我經歷polySetCoefficient時,我的以前的條目都被替換爲0。我認爲這可能是因爲我將數組中的元素設置爲0的方式,但我仔細確保將元素的前一個大小設置爲0,直到數組的新大小(不包括最後一個索引)。
struct poly *polyCreate()
{
struct poly *q;
q = malloc(sizeof(struct poly));
q->c = malloc(sizeof(double));
q->c[0] = 0.0;
q->size = 0;
//printf("polyCreate: %g\n", q->c[0]);
return q;
}
struct poly *polySetCoefficient(struct poly *p, int i, double value)
{
//printf("%d\n", i*sizeof(double));
if (p->size < i)
{
printf("Old: %d, New: %d\n", sizeof(p->c)/sizeof(double), i);
p->c = realloc(p->c, i+1*sizeof(double));
printf("New: %d \n", sizeof(p->c));
for(int l = p->size; l <= i; l++)
{
if(l != i)
{
p->c[l] = 0;
printf("set to 0\n");
}
else
{
p->c[l] = value;
printf("F:set to %g\n", p->c[i]);
}
}
printf("Did we come here?\n");
p->size = i;
} else {
p->c[i] = value;
}
printf("The %d'th coefficient is %g\n", i, p->c[i]);
printf("Cof 0: %g, Cof 1: %g, Cof 10: %g", p->c[0], p->c[1], p->c[10]);
return p;
}
在poly.h
struct poly
{
double *c;
int size, length;
};
struct poly *polyCreate();
struct poly *polyDelete(struct poly *p);
struct poly *polySetCoefficient (struct poly *p, int i, double value);
double polyGetCoefficient (struct poly *p, int i);
int polyDegree (struct poly *p);
void polyPrint (struct poly *p);
struct poly *polyCopy (struct poly *p);
struct poly *polyAdd (struct poly *p0, struct poly *p1);
struct poly *polyMultiply (struct poly *p0, struct poly *p1);
struct poly *polyPrime (struct poly *p);
double polyEval (struct poly *p, double x);
順便說一句,你使用'realloc'不正確。如果'realloc'失敗,那麼你失去了原來的指針,即你泄漏了內存。您需要首先分配給一個臨時指針。另外,在創建結構體的實例之後,爲指針成員分配一個double。爲什麼你將'size'設置爲0?這只是令人困惑,它應該是1. –
大小基本上是數組的索引,使它更容易處理,當我將它設置爲0.我爲指針成員分配一個雙重實質上創建一個數組與一個條目具有零值。我不明白代碼中的錯誤,假設realloc不會失敗。 – Maaz
好的,但請注意,size是實際上是索引的一個非常奇怪的名稱。大多數人會認爲這意味着,你知道......陣列的「大小」。 –