Alesfatalis Alesfatalis - 9 days ago 6
C Question

access pointer to double array

I have these structs:


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;


When
inputFile
is
NULL
I set the double pointer(
config.numbers
) to the array:
double numbers[] = {3,5,7};
If there is an
inputFile
I read numbers from it into the array
numberList
After that I set the pointer
config.numbers
to
numberList
. This is the code:


//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


When I print
numberList
in
else
with this for-Loop:


int z;
for(z = 0; z < lines; ++z) {
printf("%f\n", numberList[z]));
}


Everything works fine, but when I try to print the array using the pointer with this for-Loop:


int z;
for(z = 0; z < lines; ++z) {
printf("%f\n", *(config.numbers + z));
}


I get as result something like this:

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


So how do I access the pointer correctly or did I something else wrong?

EDIT:
The input file looks like this:

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


I expect the same output.

initialising Lines:

int lines = 0;

Answer

You have declared the array inside the else branch of your if and then you attempt to print it outside that scope through the pointer. It means that the array has been already destroyed when you attempt to print it.

You need to use dynamic allocation, or try to rewrite the code in a away that allows the array to be declared/defined in the same scope where you are going to print it.

Comments