我有这些结构:
typedef struct {
char *start;
char *loops;
char *tolerance;
double *numbers;
} configuration;
typedef struct {
bool help;
bool debug;
const char *configFile;
const char *inputFile;
const char *outputFile;
bool parallel;
int fragmentSize;
} options;
当inputFile
为NULL
时,我将双指针(config.numbers
)设置为数组:double numbers[] = {3,5,7};
如果有inputFile
我从中读取数字进入数组numberList
之后我将指针config.numbers
设置为numberList
。这是代码:
//Safe number list into config
if(opt.inputFile == NULL) {
config.numbers = &numbers[0];
lines = 3;
} else {
//Count lines|numbers in file
FILE* fp;
fp = fopen(opt.inputFile,"r");
int bh = 0;
while(!feof(fp))
{
bh = fgetc(fp);
if(bh == '\n')
{
lines++;
}
}
fclose(fp);
//End counting
//Read numbers from file
fp = fopen(opt.inputFile,"r");
double numberList[lines];
double number;
int n;
for (n = 0; n < lines; n++) {
fscanf(fp, "%lg", &number);
numberList[n] = number;
}
//End reading numbers from file
config.numbers = &numberList[0];
}
//End safing number list
当我使用此for循环在numberList
中打印else
时:
int z;
for(z = 0; z < lines; ++z) {
printf("%f\n", numberList[z]));
}
一切正常,但是当我尝试使用带有for-Loop的指针打印数组时:
int z;
for(z = 0; z < lines; ++z) {
printf("%f\n", *(config.numbers + z));
}
我得到的结果是这样的:
71861994.719069
28587064.020609
91127582.029965
34937973.383320
49643168.000000
0.000000
0.000000
27369248.460685
54686448.003485
93571557.380991
-nan
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
那么如何正确访问指针或者其他错误呢?
编辑: 输入文件如下所示:
95181223.701304
27539279.045323
25701472.780528
29898009.416600
72366798.330269
3326112.825110
79857126.893409
38880807.039738
8199298.711586
42132873.992498
34763372.472843
14076941.001265
79042893.824653
17188914.128202
93208812.499982
42846886.181667
80882719.243356
23444107.325489
我期待相同的输出。
初始化行:
int lines = 0;
答案 0 :(得分:2)
您已在else
的{{1}}分支内声明了数组,然后尝试通过指针将其打印到该范围之外。这意味着当您尝试打印时,阵列已经被销毁。
您需要使用动态分配,或尝试重写代码,允许在要打印它的同一范围内声明/定义数组。