C语言中不使用数组下标的内积函数
我试图为内积编写一个函数,但程序不能正常工作。 你能告诉我哪里错了吗C语言中不使用数组下标的内积函数,c,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()
#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;
}
#包括
#包括
整数内积(常数整数*a,常数整数*b,整数大小)
{
int sum=0,i;
对于(i=0;i,首先:
主菜单中:
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
*/
在函数中
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
for(i=0;i1行为未定义
//请记住,您只有两个指针可以合法地取消引用ie a和b
首先,应该初始化指针a和b,以使代码正常工作。
您将它们作为“int”值引入。因此,这些“数组”的项数为1,因此您不需要任何循环来计算总和
除此之外,最好不要使用像这样的复杂结构
*(a+i)
最好(也更容易阅读)说:
相反
此外,代码中可能存在溢出问题-如果输入了两个值(在a[i]和b[i]中),它们产生的总和大于“int”类型可以包含的总和(大于2^32),该怎么办?
您正在将两个整数之和计算为第三个整数,而不进行任何检查。在生产软件中,这可能会导致安全漏洞。a
和b
未初始化使用。并且每个整数中只有一个(a
和b
),使*(a+i)
当size>1时,b-派生调用UB
问题明确地说“不使用数组下标”,因此建议使用下标不是很有效。这只是一个如何编写可读性更强的代码的建议。我如何初始化它们?比如int a=5,b=6;
或者使用scanf读取它们的值。
a[i]