本文介绍了不使用C中的数组下标内积函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试着写了内积机能的,但程序不工作正常。
你能电话我哪里是我的错?
#包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;INT inner_product(const int的*一,const int的* B,INT大小)
{
INT总和= 0,I; 对于(i = 0; I<大小; ++ I)
总和+ = *(A + I)* *(B + I); 返回总和;
}
诠释的main()
{
INT N,A,B;
的printf(有多少元素做你想做的存储?);
scanf函数(%d个,&安培; N); 的printf(%d个,inner_product(安培;一,和b,N));
系统(暂停);
返回0;
}
解决方案
刚入手:
在主要的:
INT N,A,B; // A和b的未初始化
。
scanf函数(%d个,&安培; N); //想想有什么用n个在这里。
。
的printf(%d个,inner_product(安培;一,和b,N));
/ *您通过了A和B的地址,这是确定的,但在他们的价值
*店是不确定按照标准
* /
在功能
为(i = 0; I<大小; ++ I)
总和+ = *(A + I)* *(B + I); //访问内存越界的大小大于1行为是不确定的
//记住,你只有两个三分球,你可以合法解除引用,即a和b
I try to write a fuction for inner product, but program doesnt work properly.Can you tel me where is my mistake?
#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;
}
解决方案
Just to start with :
In main:
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
*/
In the function
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
这篇关于不使用C中的数组下标内积函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!