2016-05-05 6 views
-3

内積用の関数を書き込もうとしましたが、プログラムが正しく機能しません。 私の間違いはどこですか?Cで配列添字を使用しない内積関数

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

int inner_product(const int *a, const int *b, int size) 
{ 
    int sum = 0, i; 

    for (i=0; i<size; ++i) 
    sum += *(a+i) * *(b+i); 

    return sum; 
} 


int main() 
{ 
    int n, a, b; 
    printf("How many elements do you want to store? "); 
    scanf("%d",&n); 

    printf("%d",inner_product(&a,&b,n)); 
    system("pause"); 
    return 0; 
} 
+4

「a」と「b」は未初期化で使用されます。 – haccks

+1

そして、それぞれ(* a + i)*を1つだけ持ち、b *派生はUBを呼び出します。 – WhozCraig

答えて

0

だけで起動する:メインで

:機能まず

for (i=0; i<size; ++i) 
sum += *(a+i) * *(b+i); // Accessing the memory out of bound for size>1 behavior is undefined 
// Remember you have only two pointers which you can legally dereference ie a and b 
+0

どうすればそれらを初期化できますか? – user6200763

+0

'int a = 5、b = 6;'に似ているか、scanfを使って値を読み込みます。 – sjsam

0

int n, a, b; // a & b are not initialized 
. 
scanf("%d",&n); // Think what is the use of n here. 
. 
printf("%d",inner_product(&a,&b,n)); 
/* You passed address of a and b, this is OK but the value they 
* store is indeterminate as per the standard 
*/ 

を、ポインタa、bが初期化されなければなりませんその作品を作るコードの作業。 "int"値としてそれらを導入します。したがって、これらの「配列」のアイテム数は1です。したがって、合計を計算するためのサイクルは必要ありません。

a[i] 

代わりに:それに加えて

、言う方が良い(とはるかに簡単に読める)である

*(a+i) 

のような複雑な構造を使用しないためにはるかに優れています。

また、オーバーフローの問題がコード内に存在する可能性があります。[int]型よりも大きな合計を生成する2つの値([i]とb [i] 2^32より)? 2つの整数の合計をチェックなしで3番目の整数に計算しています。プロダクションソフトウェアでは、セキュリティ上の欠陥につながる可能性があります。

+0

質問には「配列添え字を使わない」と書かれているので、添え字を使って推薦するのはあまり効率的ではありません。 –

+0

もっと読みやすいコードを書く方法を提案するだけです。 –

関連する問題