我写了这个代码作为一个家庭作业问题,希望我通过使用指针算法-NOT SUBSCRIPTING-来访问数组元素来编写内部产品。但是,程序不允许我输入第三个元素后输入数字。为什么呢?
int inner_product(int *a, int *b, int size)
{
int sum = 0, i;
for (i=0; i<size; i++)
{
printf("enter value for first array: ");
scanf("%d",*(a+i));
}
for (i=0; i<size; i++)
{
printf("enter value for second array: ");
scanf("%d",*(b+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);
a=(int *)malloc(n*sizeof(int));
b=(int *)malloc(n*sizeof(int));
printf("%d\n",inner_product(a,b,n));
free(a);
free(b);
}
答案 0 :(得分:0)
在*(a+i)
的来电中使用*(b+i)
和scanf
是不对的。他们需要(a+i)
和(b+i)
。
由于您将错误的参数传递给scanf
,您正在遇到未定义的行为。
您需要提高编译器警告级别以在编译时检测这些错误。
当我使用gcc -Wall
时,我收到以下警告:
soc.c: In function ‘inner_product’:
soc.c:11:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%d",*(a+i));
^
soc.c:11:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
soc.c:17:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%d",*(b+i));
^
soc.c:17:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
答案 1 :(得分:0)
您可以修复警告。
$ gcc main.c
main.c: In function ‘inner_product’:
main.c:11:15: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%d",*(a+i));
^
main.c:17:15: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%d",*(b+i));
如果我修正了警告,那么我可以输入4个元素:
$ ./a.out
How many elements do you want to store? 4
enter value for first array: 2
enter value for first array: 3
enter value for first array: 4
enter value for first array: 5
enter value for second array: 3
enter value for second array: 4
enter value for second array: 5
enter value for second array: 6
68
我刚刚将调用从int更改为指针。
#include <stdio.h>
#include <stdlib.h>
int inner_product(int *a, int *b, int size)
{
int sum = 0, i;
for (i=0; i<size; i++)
{
printf("enter value for first array: ");
scanf("%d",(a+i));
}
for (i=0; i<size; i++)
{
printf("enter value for second array: ");
scanf("%d",(b+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);
a = (int *) malloc(n * sizeof(int));
b = (int *) malloc(n * sizeof(int));
printf("%d\n", inner_product(a, b, n));
free(a);
free(b);
}