【问题标题】:C Program - pointer array multiplicationC 程序 - 指针数组乘法
【发布时间】:2015-10-04 19:32:54
【问题描述】:

这个程序应该采用 2 个数组并对数组中的每个元素进行点积。

如果 n 的索引小于 5,我的程序就可以了;但是,一旦数组的索引大于 5,只有第一个数组中的第一个元素是错误的(我通过在函数中添加 printf 语句进行检查)。我不知道如何修复这个错误。

#include <stdio.h>

void multi_vec(int *v1, int *v2, int *v3, int n);
int main(void)
{
    int n, i;
    int v1[n];
    int v2[n];
    int v3[n];
    printf("Enter the length of the two vectors\n");
    scanf("%d", &n);
    printf("Enter numbers for the first array\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &v1[i]);
    }
    printf("Enter numbers for the second array\n", n);
    for (i = 0; i < n; i++) {
         scanf("%d", &v2[i]);
    }

    multi_vec(v1, v2, v3, n);

    for (i = 0; i < n; i++) {
        printf("%d", v3[i]);
    }
    printf("\n");
    return 0;
}

void multi_vec(int *v1, int *v2, int *v3, int n)
{
    int i;
    for (i = 0; i < n; i++) {
        *(v3+i) = *(v1+i) * *(v2+i);
    }
}

【问题讨论】:

  • n 未初始化 rextester.com/AJDX1741
  • Int v1[n] 是非法的。即使 n 已初始化
  • @machine_1:你更像是一个 C++ 人,不是吗? VLA 在 c 中是可以的。

标签: c arrays pointers dot-product


【解决方案1】:

正确的代码

#include <stdio.h>

void multi_vec(int *v1, int *v2, int *v3, int n);
int main(void)
{
    int n, i;
    printf("Enter the length of the two vectors\n");
    scanf("%d", &n);
    int v1[n],v2[n],v3[n];     //you didn't initialize n
    printf("Enter numbers for the first array\n");    //printf statements had extra ',n'

    for (i = 0; i < n; i++) {
        scanf("%d", &v1[i]);
    }
    printf("Enter numbers for the second array\n");    //printf statements had extra ',n'
    for (i = 0; i < n; i++) {
         scanf("%d", &v2[i]);
    }

    multi_vec(v1, v2, v3, n);

    for (i = 0; i < n; i++) {
        printf("%d ", v3[i]);
    }
    printf("\n");
    return 0;
}

void multi_vec(int *v1, int *v2, int *v3, int n)
{
    int i;
    for (i = 0; i < n; i++) {
        *(v3+i) = *(v1+i) * *(v2+i);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多