繁体   English   中英

在C中将整数数组作为函数参数传递

[英]Passing an array of integers as function parameter in C

请帮助我,我对此感到困惑。 我有一个必须将两个大小为n的整数的数组求和的函数,并且我必须将每个数组的第一个元素作为该函数的参数传递,这是否关闭了?

 12 void sumVect(int * v[], int * w[] ,int n)
 13 //adds the second vector to the first vector; the vectors v and w have exactly n components
 14 {
 15         int i;
 16         for(i=0;i<n;i++)
 17         {
 18                 *v[i]+=*w[i];
 19         }
 20 
 21 }

我会给你整个代码

#include <stdio.h>

void sumVect(int * v[], int * w[] ,int n)
//adds the second vector to the first vector; the vectors v and w have exactly n components
{
    int i;
    for(i=0;i<n;i++)
    {
        *v[i]+=*w[i];
    }

}


int main()
{   
    int i,j;
    int n = 4;  //the size of a vector
    int k = 5;  //the number of vectors
    int v[k][n];    //the vector of vectors

    printf("How many vectors? k=");
    scanf("%d",&k);

    printf("How many components for each vector? n=");
    scanf("%d",&n);

    for(i=1;i<=k;i++)   //read the content of each vector from the screen
    {
        printf("\nv%d   |\n_____|\n",i);

        for(j=0;j<n;j++)
        {
            printf("v%d[%d]=",i,j);
            scanf("%d", &v[i][j]);
        }
    }

    for(j=1;j<k;j++)
    {
        sumVect(&v[j], &v[j+1], n);
        for(i=0;i<n;i++)
        {
            printf("%d",v[j][i]);
        }
    }


    return 0;
}

注意,您传递的是int []类型,但函数中的形式参数是int *[] 因此,您的签名应为:

void sumVect(int v[], int w[] ,int n)

要么

void sumVect(int *v, int *w,int n)

你也应该在函数中访问它们

v[i] + w[i]因为vw均为int *int [] (取决于形式参数)

此外,在致电时,您还应该这样做:

sumVect(v[j], v[j+1], n);

要么

sumVect(&v[j], &v[j+1], n);

这是因为当v[j]int []类型时, &v[i]v[i]将为相同的地址。

这是函数sumVect的更正版本。

void sumVect(int * v, int * w ,int n)
//adds the second vector to the first vector; the vectors v and w have exactly n components
{
    int i;
    for(i=0;i<n;i++)
    {
        v[i]+=w[i];
    }

}

但是整个您都需要进行一些更正。 看这段代码:

int n = 4;  //the size of a vector
int k = 5;  //the number of vectors
int v[k][n];    //the vector of vectors

printf("How many vectors? k=");
scanf("%d",&k);

printf("How many components for each vector? n=");
scanf("%d",&n);

这是大小为5x4的2维数组的分配,然后您的程序询问用户数组的实际大小。 解决它的最简单方法是使用数组的堆分配。 这是固定代码:

int n = 4;  //the size of a vector
int k = 5;  //the number of vectors
int **v = NULL;    //the vector of vectors

printf("How many vectors? k=");
scanf("%d",&k);

printf("How many components for each vector? n=");
scanf("%d",&n);
v = malloc(sizeof(int*), k);
for( int i = 0; i < k; ++i)
   v[i] = malloc(sizeof(int), n);

最后,您应该以类似的方式释放分配的内存,但是让它作为您的家庭作业。

数组和指针在c中通常被视为同一事物。 数组变量保存指向数组的指针,[]表示法是指针算术的快捷方式。

请注意,n应该是无符号类型。

void sumVect(int * v, int * w, uint n)
{
    while (n--)
    {
        *v++ += *w++;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM