简体   繁体   English

在C中为动态浮点数组赋值

[英]Assigning values to dynamic floating point array in C

I used malloc() to make an array of floating point numbers like so: 我使用malloc()来创建一个浮点数数组,如下所示:

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]); 到目前为止,基于我有限的知识,似乎以上情况很好,但是当我尝试使用这样的数组时: 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. x1之后括号中的N是一个通常会递增的变量,但出于测试目的,我引用了所有这些并且只使用了数组范围内的任何数字,例如3。 When I try to do this, the program compiles and runs fine until it hits the fscanf line of code. 当我尝试这样做时,程序编译并运行正常,直到它到达fscanf代码行。 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]); 我尝试使用我的动态数组,因为x1[3] = 12345似乎有效,因为printf("%f",x1[3]); outputted 12345 like it was supposed to. 像它应该的那样输出12345 This leads me to believe the problem lies within fscanf(stl,"%f",x1[N]); 这让我相信问题在于fscanf(stl,"%f",x1[N]); but I have no clue why. 但我不知道为什么。

Thanks in advance for any advice, it is greatly appreaciated. 在此先感谢任何建议,它是非常有用的。

With the scanf family, you need to provide the address of the variable you want populated, such as: 使用scanf系列,您需要提供要填充的变量的地址 ,例如:

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

From the C11 standard 7.20.6.2 The fscanf function / 12 (my emphasis): C11标准7.20.6.2 The fscanf function / 12 (我的重点):

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. a,e,f,g:匹配可选带符号的浮点数,无穷大或NaN,其格式与strtod函数的主题序列的预期格式相同。 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. 从C中显式地转换来自malloc的返回值并不是一个好主意。它可以隐藏某些微妙的错误,并且C将很乐意在没有它的情况下进行隐式转换。
  • 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. 检查scanf系列的返回值通常是个好主意,因为它可以为您提供成功扫描的项目数。 If that's not what you asked for, you should take appropriate action. 如果那不是你要求的,你应该采取适当的行动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM