Home > Enterprise >  Why is there no & in the scan function?
Why is there no & in the scan function?

Time:11-25

This is the programm I wrote:

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

void meanVariance(double* x, int n, double* mean, double* variance);
double* scanVector(int length);


void meanVariance(double* x, int n, double* mean, double* variance){
    double sum = 0;

    for (int i = 0; i < n; i  ){
        sum  = x[i];
    }

    *mean = sum / ((double)n);

    sum = 0;

    for (int i = 0; i < n; i  )
    {
        double sq = x[i] - *mean;
        sum  = sq * sq;
    }

    if (n != 1)
    {
        *variance = sum / ((double)n );
    }
    else
    {
        *variance = 1;
    }

}


int main() {
    double *x = malloc(sizeof(double)), mean = 0, variance = 0;
    int n = 0;
    do {
        n  ;
        x = realloc(x, sizeof(double) * (n));
        printf("Type in the %d- Number 


: ", n);
        scanf("%lf", (x (n-1)));
        meanVariance(x, n, &mean, &variance);
        printf("Mittelwert: %f\n", mean);
        printf("Varianz: %f\n", variance);
    } while(*(x (n-1)) != 0);
    free(x);
}

I don't unterstand why there is no & in the scanf function. The program works but I just don't unterstand why cause the & is missing. I'm guessing it has something to do with the pointer x however i'm not sure at all.

CodePudding user response:

You only need & if you need to take the address of a value, that is, produce a pointer to that value. But x is already a pointer, so there is no need for &. It would be quite wrong to use & in this case, because you'd end up with a pointer to a pointer!

There is also some pointer arithmetic going on: x (n-1) advances the pointer by n-1 positions in memory, each position being sizeof(double) bytes. If you view x as an array, it's the same as &x[n-1]; that is, the address of the n-1th element in the array.

CodePudding user response:

x (n-1) - this is pointer arithmetic (study the term).

The [] operator is specified with the guarantee that array[i] (readable) is 100% equivalent to *((array) (i)) (unreadable).

In your case &x[n-1] is the same as &*( (x) (n-1) ). The & and * cancel each other out and what remains is x (n-1).

So we can unslopify the code using readable form like this: scanf("%lf", &x[n-1]);

  • Related