Reading floats into an array

后端 未结 6 840
[愿得一人]
[愿得一人] 2021-01-22 00:39

How could I read let\'s say 10 floats and store them in an array without wasting any memory?

6条回答
  •  既然无缘
    2021-01-22 01:15

    Aha. It's not reading the floats that's the problem, it's the memory. You read in i, and you need an array that holds exactly i floats.

    This really does smell like homework, which is fine, but I'm too much the teacher to give you the full answer. So I'll tell you, what you need is a C function named malloc() and a C operator (it looks like a function but it's actually built into the language) named sizeof.

    Have a look at this tutorial.


    Yup, you got it there. Here's the code from your comment, formatted.

    int n,index;
    float temp;
    scanf("%d",&n);
    float *pValues=(float *)calloc(n,sizeof(float));
    for(index=0;index

    I'd do it with two changes:

    1. Its more idiomatic to use malloc for anything besides characters
    2. In C, arrays and pointers have a very close relationship; in fact *(pValues+index) is exactly equivalent to pValues[index].

    So I'd rewrite this as:

    int n,index;
    float temp;
    scanf("%d",&n);
    float *pValues=(float *)malloc(n*sizeof(float));
    for(index=0;index

    Let's look at one more transformation of the code. You have pValues, which is a pointer to float. You have &temp, which is also a pointer to float, because & is the address-of operator and temp is a float. AND, you're just doing pointer arithmetic with your index. So, we could rewrite this one more time as:

    int n,index;    // Don't need temp
    scanf("%d",&n);
    float *pValues=(float *)malloc(n*sizeof(float));
    for(index=0;index

    Now, quiz question: what would happen if you made the loop

    for(index=0;index

提交回复
热议问题