I'm trying to read some float values as an array to a struct member as shown below:
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <stdio.h>
#define MAX_IN 10
typedef struct S_t S_t;
struct S_t {
float *sptr;
uint32_t ns;
};
S_t *getInputS(char *sdfile)
{
FILE *inSFP;
float fvls[MAX_IN];
static S_t inS;
int n;
inSFP = fopen(sdfile, "r");
if (inSFP == NULL) {
printf("\nFailed to open input file...!!!\n");
}
else {
n = 0;
while (fscanf(inSFP, "%f", &fvls[n]) != EOF) {
printf("fvls[%d] = %f\n", n, fvls[n]);
n++;
}
printf("\nScanned all inputs....\n");
inS.ns = (uint32_t) n;
inS.sptr = (float *) malloc(n * sizeof(float));
inS.sptr = fvls;
for(int i = 0; i < n; i++)
printf("inS.sptr[%d] = %f\n", i, inS.sptr[i]);
printf("\nInput read from file %s....\n", sdfile);
fclose(inSFP);
printf("\nClosed file...");
}
return &inS;
}
int main(int argc, char *argv[])
{
S_t *inpS = malloc(sizeof(*inpS));
inpS->sptr = malloc(MAX_IN * sizeof(inpS->sptr));
S_t *outS = malloc(sizeof(*outS));
outS->sptr = malloc(MAX_IN * sizeof(outS->sptr));
static uint32_t n;
char *inFN = argv[1];
char *outFN = argv[2];
inpS = getInputS(inFN);
printf("\nContent from main : \n");
n = inpS->ns;
for(int i = 0; i < n; i++)
printf("%f", *(inpS->sptr + i));
// printf("%f", inpS->sptr[i]);
printf("\nS structure updated (ns = %d)....\n", n);
return 0;
}
This returns the following:
fvls[0] = 0.430000
fvls[1] = 0.563210
fvls[2] = 0.110000
fvls[3] = 1.230000
fvls[4] = -0.034000
Scanned all inputs....
inS.sptr[0] = 0.430000
inS.sptr[1] = 0.563210
inS.sptr[2] = 0.110000
inS.sptr[3] = 1.230000
inS.sptr[4] = -0.034000
Input read from file in.txt....
Closed file...
Content from main :
-0.0000000.0000000.0000000.000000-nan
S structure updated (ns = 5)....
Input values (Original Input):
[0.000000, 0.000000, -0.000000, 0.000000, -0.000000]
The values are indeed read from the input file by the function getInputS() correctly, but on return the member sptr's values are returned incorrectly.
I am using a static variable of type S_t to store the values so that the value is retained. Inspite of that, the values seem to have lost! What am I doing wrong here? How do I fix this?
0.43 0.56321 0.11 1.23 -0.034.inS.sptr = fvls;what happens to fvls when you exit the function scope?fvalsis kind of temporary variable that is destroyed when the function is exited. I just wanted it for counting the array numbers.