简体   繁体   中英

Can somone please explain this to me

For n=3 and a={1,2,3},b={4,5,6} its supposed to calculate 1*4+2*5+3*6 . I don't understand why does it work because p is a pointer and p=produs(a,b,n) means that the address of p becomes the value returned by produs.

#include <stdio.h>
#include <conio.h>
void citire(int *x,int *n)
{
    for(int i=1; i<=*n; i++)
        scanf("%d",&x[i]);
}

int produs(int *a,int*b,int n)
{
    int produs=0;
    for(int i=1;i<=n;i++)
        produs=a[i]*b[i]+produs;
    return produs;
}

int main()
{
    int n;
    int*p;
    scanf("%d",&n);

    int *a=(int*)malloc(n*sizeof(int));
    int *b=(int*)malloc(n*sizeof(int));
    citire(a,&n);
    citire(b,&n);
    p=produs(a,b,n);
    printf("%d",p);

    return 0;
}

When you do:

size_t size = 10;
int* x = calloc(size, sizeof(int));

You get an array x with 10 items in it, indexed 0..9, not 1..10. Here calloc is used to make it abundantly clear what's being requested instead of doing multiplication that can be mysterious or obtuse.

As such, to iterate:

for (int i = 0; i < size; ++i) {
  x[i] ...
}

You have a number of off-by-one errors in your code due to assuming arrays are 1..N and not 0..(N-1).

Putting it all together and cleaning up your code yields:

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

    void citire(int *x, size_t s)
    {
        for(int i=0; i < s; i++)
            scanf("%d", &x[i]);
    }

    int produs(int *a, int* b, size_t s)
    {
        int produs = 0;

        for(int i = 0; i < s; i++)
            produs = a[i] * b[i] + produs;

        return produs;
    }

    int main()
    {
        int n;
        scanf("%d",&n);

        int* a = calloc(n, sizeof(int));
        int* b = calloc(n, sizeof(int));

        citire(a, n);
        citire(b, n);

        // produs() returns int, not int*
        int p = produs(a,b,n);
        printf("%d", p);

        return 0;
    }

You're using pointers in places where pointers don't belong. In C passing a pointer to a single value means "this is mutable", but you don't change those values, so no pointer is necessary nor advised.

Try and use size_t as the "size of thing" type. That's what's used throughout C and it's an unsigned value as negative indexes or array lengths don't make any sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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