簡體   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