gpt4 book ai didi

c - C 中不使用数组下标的内积函数

转载 作者:行者123 更新时间:2023-11-30 21:08:46 25 4
gpt4 key购买 nike

我尝试编写一个内积函数,但程序无法正常工作。你能告诉我我的错误在哪里吗?

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

最佳答案

首先:

主要:

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

关于c - C 中不使用数组下标的内积函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37058242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com