1

I used malloc() to make an array of floating point numbers like so:

float*x1;

x1 = (float*)malloc((vertexes/3)*sizeof(float)); 

if(x1 == NULL)
{
    printf("Out Of Memory");
    getchar(); return(1);
}

So far, it seems like the above is fine based on my limited knowledge, however when I attempt to use that array like this: fscanf(stl,"%f",x1[N]); it does not work. The N in brackets after the x1 is a variable that normally gets incremented, but for testing purposes I quoted out all that and just used any number that was within the range of the array like 3 for example. When I try to do this, the program compiles and runs fine until it hits the fscanf line of code. at that point it crashes and windows says its trying to find a solution to the problem. I tried using my dynamic array by putting x1[3] = 12345 which seemed to work, because printf("%f",x1[3]); outputted 12345 like it was supposed to. This leads me to believe the problem lies within fscanf(stl,"%f",x1[N]); but I have no clue why.

Thanks in advance for any advice, it is greatly appreaciated.

1 Answers1

3

With the scanf family, you need to provide the address of the variable you want populated, such as:

fscanf (stl, "%f", &(x1[N]));

From the C11 standard 7.20.6.2 The fscanf function / 12 (my emphasis):

a,e,f,g: Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.


And, just a couple of other points:

  • it's not a good idea to explicitly cast the return value from malloc in C. It can hide certain subtle errors, and C will happily implicitly cast without it.
  • it's usually a good idea to check the return value from the scanf family since it gives you the number of items successfully scanned. If that's not what you asked for, you should take appropriate action.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Thank-You paxdiablo, it works exactly as it should now. I was just wondering though, did the way I have it try to set a value to the pointer instead of the array? And as for the `malloc` thing I don't understand what you mean. I just googled how to make dynamic arrays and then I copied it and changed the parameters. – user1888665 Aug 14 '13 at 01:51
  • @user1888665: on the `malloc` (second) question, see http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc. Re the first question, it would have taken the current (arbitrary) _value_ of `x1[N]` and used that as a pointer to populate an (arbitrary) memory block. Not a good idea :-) – paxdiablo Aug 14 '13 at 01:55