【发布时间】:2019-05-13 01:29:50
【问题描述】:
我无法从用另一个 c 程序编写的文件中获取变量/元素的值以存储到正在运行的 c 程序的变量/元素中。 在将变量“i”读入程序(这是一个已经确定并存储在文件“inventory.txt”中的整数)时,我不断收到分段错误。 “i”表示正在打印的数组的元素数量(大小)。这是损坏的代码):。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int l, k;
int *pn, *arraysize, *q;
float *p;
FILE *fp = fopen( "inventory.txt", "r+b" ); //declarations and I open up the binary file "inventory.txt"
if ( fp == NULL )
{ //check file
printf( "nah" );
exit( EXIT_FAILURE );
}
*arraysize = fread( &arraysize, sizeof( int ), 1, fp ); //set arraysize in this program equal to i in the binary file inventory.txt?????? Here is where I get segmentation fault
printf( "marker1" ); //place marker, I am not getting to this point when running the program
for ( l = 0; l < *arraysize; l++ )
{
q[l] = fread( &q[l], sizeof( int ), arraysize, fp ); //set array elements ("arraysize" of them) pn, q, and p to the array elements of the same name in binary file inventory.txt
p[l] = fread( &p[l], sizeof( int ), arraysize, fp );
pn[l] = fread( &pn[l], sizeof( int ), arraysize, fp );
}
printf( "Below are the items in your inventory.\nPart#\tQuantity\tPrice\n" ); //print out the values
for ( l = 0; l < *arraysize; l++ )
{
printf( "%5d\t", pn[l] );
printf( "%8d\t", q[l] );
printf( "%9.2f\n", p[l] );
}
return 0;
}
【问题讨论】: