[英]Adding a struct to an array using a pointer
我對C語言相當新,並且通常使用指針分配內存。 無論如何,我正在嘗試讀取文件,將這些值放在結構中等等。我確切地知道我想要做什么,當然程序運行但是輸出不正確以及某種混亂的數字和字母。
有一個文本文件,其中包含每行的新信息。 每行代表一個對象。
這是文件中的一行可能看起來如何:
meat sirloin 6.55 8 8.50 4
總的來說,我希望能夠將所有PRODUCT
對象存儲在一個數組中(所以我有一個結構數組)。 所以我試圖用指針分配內存,使用行數,然后將指針發送到一個名為read的函數。 在讀取中,我通過指針將每個結構添加到數組中。 程序沒有崩潰,輸出不正確,我不知道為什么不。 這是指針的問題。 如果有人能幫助我,我會非常感激。 任何幫助都會很棒。
//prototype
void read(pointerToArr);
typedef struct
{
char supType[15];
char prodName[15];
double wholePrice;
int quantWhole;
double retPrice;
int retProdQuantity;
}PRODUCT;
FILE *fr;
int lineCount = 0;
int main()
{
PRODUCT *ptr;
int i;
char check[50];
fr = fopen("ttt.txt", "r");
while(fgets(check, sizeof(check), fr)!= NULL)
{
if(check[0] != '\n')
{
lineCount++;
}
}
// allocate memory for array based on line count.
PRODUCT prodContainter[lineCount];
ptr = (PRODUCT*)malloc(sizeof(PRODUCT)*lineCount);
ptr = prodContainter;
read(ptr);
//print after adding to array via pointer from other
//function. this was a test.
for(i = 0; i < lineCount; i++)
{
printf("%s ", prodContainter[i].supType);
printf("%s ", prodContainter[i].prodName);
printf("%f ", prodContainter[i].wholePrice);
printf("%d ", prodContainter[i].quantWhole);
printf("%f ", prodContainter[i].retPrice);
printf("%d\n\n", prodContainter[i].retProdQuantity);
}
return 0;
}
void read(PRODUCT *pointerToArr)
{
// objective in this method is to read in data from the file, create an object for every line and
// then use the pointer array to add those objects to prodConstainer up above.
char supplyName[15];
char productName[15];
double wholeP = 0;
int quantityWhole = 0;
double retailPrice = 0;
int retailProductQuant = 0;
while(fscanf(fr, "%s %s %lf %d %lf %d", supplyName, productName, &wholeP, &quantityWhole, &retailPrice, &retailProductQuant) == 6)
{
PRODUCT record;
int i;
strcpy(record.supType, supplyName);
strcpy(record.prodName, productName);
record.wholePrice = wholeP;
record.quantWhole = quantityWhole;
record.retPrice = retailPrice;
record.retProdQuantity = retailProductQuant;
for(i = 0; i < lineCount; i++)
{
pointerToArr[i] = record;
}
}
fclose(fr);
}
你永遠不會回卷文件,所以你計算行數后的所有讀數都會失敗。
你正在打印的是內存中發生的事情。
當然,有很多方法可以解決這個問題。
rewind()
回放文件 read()
函數(其名稱與POSIX標准函數碰撞)重新打開文件。 這還涉及刪除可怕的全局變量fr
。 ptr
數組在必要時增長(參見realloc()
)。 此外, 您應該避免在C中強制轉換malloc()
的返回值 。 這個:
ptr = (PRODUCT*)malloc(sizeof(PRODUCT)*lineCount);
寫得更好:
ptr = malloc(lineCount * sizeof *ptr);
這消除了強制轉換,並且還在指向的類型的值上使用sizeof
來自動計算要分配的正確字節數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.