像这样调试程序的第一条规则是打印关键数据。在这里,最关键的数据项可能是 的值n
。您没有说明如何调用程序,但是您n
从参数列表 ( int n = atoi(argv[1]);
) 中读取,而没有检查是否有参数。您看到的行为与 一致n == 0
。因此,您可以通过以下方式帮助自己:
#include <stdio.h>
#include <stdlib.h>
int inner(int A[], int B[], int n)
{
int product = 0;
int i;
printf("n = %d\n", n);
for (i = 0; i < n; i++)
{
printf("P = %2d, A[%d] = %d, B[%d] = %d\n", product, i, A[i], i, B[i]);
product = product + A[i] * B[i];
}
return product;
}
int main( int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s number\n", argv[0]);
return 1;
}
int n = atoi(argv[1]);
int *A, *B;
int r1, c1, i, j, r2, c2, product;
printf("Enter values for r1 and c1 for vector A: ");
scanf("%d %d", &r1, &c1);
printf("r1 = %d, c1 = %d\n", r1, c1);
A = (int *)malloc(n * sizeof(int) * r1 * c1);
for (i = 0; i < r1; i++)
for (j = 0; j < c1; j++)
A[i*c1+j] = i + j;
printf("\nEnter values for r2 and c2 for vector B: ");
scanf("%d %d", &r2, &c2);
printf("r2 = %d, c2 = %d\n", r2, c2);
B = (int *)malloc(n * sizeof(int) * r2 * c2);
for (i = 0; i < r2; i++)
for (j = 0; j < c2; j++)
B[i*c2+j] = i + j; // Not A again!
printf("n = %d\n", n);
product = inner(A, B, n);
printf("\nThe inner product of the two vectors is %d\n\n", product);
return 0;
}
使用bash
(所以当程序提示我时我不必继续输入数字),您可以获得示例输出,例如:
$ for i in $(seq 6 9); do echo; ./cp $i <<< "3 4 5 5"; done
Enter values for r1 and c1 for vector A: r1 = 3, c1 = 4
Enter values for r2 and c2 for vector B: r2 = 5, c2 = 5
n = 6
n = 6
P = 0, A[0] = 0, B[0] = 0
P = 0, A[1] = 1, B[1] = 1
P = 1, A[2] = 2, B[2] = 2
P = 5, A[3] = 3, B[3] = 3
P = 14, A[4] = 1, B[4] = 4
P = 18, A[5] = 2, B[5] = 1
The inner product of the two vectors is 20
Enter values for r1 and c1 for vector A: r1 = 3, c1 = 4
Enter values for r2 and c2 for vector B: r2 = 5, c2 = 5
n = 7
n = 7
P = 0, A[0] = 0, B[0] = 0
P = 0, A[1] = 1, B[1] = 1
P = 1, A[2] = 2, B[2] = 2
P = 5, A[3] = 3, B[3] = 3
P = 14, A[4] = 1, B[4] = 4
P = 18, A[5] = 2, B[5] = 1
P = 20, A[6] = 3, B[6] = 2
The inner product of the two vectors is 26
Enter values for r1 and c1 for vector A: r1 = 3, c1 = 4
Enter values for r2 and c2 for vector B: r2 = 5, c2 = 5
n = 8
n = 8
P = 0, A[0] = 0, B[0] = 0
P = 0, A[1] = 1, B[1] = 1
P = 1, A[2] = 2, B[2] = 2
P = 5, A[3] = 3, B[3] = 3
P = 14, A[4] = 1, B[4] = 4
P = 18, A[5] = 2, B[5] = 1
P = 20, A[6] = 3, B[6] = 2
P = 26, A[7] = 4, B[7] = 3
The inner product of the two vectors is 38
Enter values for r1 and c1 for vector A: r1 = 3, c1 = 4
Enter values for r2 and c2 for vector B: r2 = 5, c2 = 5
n = 9
n = 9
P = 0, A[0] = 0, B[0] = 0
P = 0, A[1] = 1, B[1] = 1
P = 1, A[2] = 2, B[2] = 2
P = 5, A[3] = 3, B[3] = 3
P = 14, A[4] = 1, B[4] = 4
P = 18, A[5] = 2, B[5] = 1
P = 20, A[6] = 3, B[6] = 2
P = 26, A[7] = 4, B[7] = 3
P = 38, A[8] = 2, B[8] = 4
The inner product of the two vectors is 46
$
回显输入和中间结果是调试程序的一种基本但强大的技术。