繁体   English   中英

有人可以向我解释一下吗

[英]Can somone please explain this to me

对于n=3a={1,2,3},b={4,5,6}它应该计算1*4+2*5+3*6 我不明白为什么它会起作用,因为 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;
}

当你这样做时:

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

你得到一个包含 10 个项目的数组x ,索引为 0..9,而不是 1..10。 在这里, calloc用于使请求的内容非常清楚,而不是进行神秘或迟钝的乘法。

因此,要迭代:

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

由于假设数组为 1..N 而不是 0..(N-1),您的代码中存在大量一对一错误。

把它们放在一起并清理你的代码会产生:

    #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;
    }

您在不属于指针的地方使用指针。 在 C 中,将指针传递给单个值意味着“这是可变的”,但您不会更改这些值,因此不需要也不建议使用指针。

尝试使用size_t作为“事物大小”类型。 这就是整个 C 中使用的内容,它是一个无符号值,因为负索引或数组长度没有任何意义。

暂无
暂无

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

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