简体   繁体   English

有人可以向我解释一下吗

[英]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 .对于n=3a={1,2,3},b={4,5,6}它应该计算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.我不明白为什么它会起作用,因为 p 是一个指针,而p=produs(a,b,n)意味着 p 的地址成为 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.你得到一个包含 10 个项目的数组x ,索引为 0..9,而不是 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.在这里, calloc用于使请求的内容非常清楚,而不是进行神秘或迟钝的乘法。

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).由于假设数组为 1..N 而不是 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.在 C 中,将指针传递给单个值意味着“这是可变的”,但您不会更改这些值,因此不需要也不建议使用指针。

Try and use size_t as the "size of thing" type.尝试使用size_t作为“事物大小”类型。 That's what's used throughout C and it's an unsigned value as negative indexes or array lengths don't make any sense.这就是整个 C 中使用的内容,它是一个无符号值,因为负索引或数组长度没有任何意义。

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

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