我对 C 语言和一般的内存分配/使用指针相当陌生。不管怎样,我正在尝试读取文件,将这些值放入结构中,等等。我确切地知道我想要做什么,当然程序会运行,但输出不正确,并且出现某种困惑的数字和字母。
有一个文本文件,其中每行都有新信息。每一行代表一个对象。
文件中的一行可能如下所示:
meat sirloin 6.55 8 8.50 4
Overall I want to be able to store all of my PRODUCT
objects in an array (so I have an array of structs). So I attempted to allocate memory with a pointer, use a line count, and then send the pointer to a function called read. In read I add each struct to the array via a pointer. The program doesn't crash, the output is just not correct and I have no clue why not. It's prob something with pointers. If anyone could help me I would really appreciate it. Any help at all would be great.
//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()
)。
此外,you should really avoid casting the return value of malloc()
in C 。这:
ptr = (PRODUCT*)malloc(sizeof(PRODUCT)*lineCount);
最好写成:
ptr = malloc(lineCount * sizeof *ptr);
这消除了强制转换,并且还对指向的类型的值使用 sizeof
来自动计算要分配的正确字节数。
关于c - 使用指针将结构体添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14630604/