通过将向量作为参数传递给c中的函数来读取向量值

时间:2016-09-12 11:39:23

标签: c

我试图通过将它们作为对函数的引用来读取文件中的2个向量及其长度。问题是我收到类型错误:"访问冲突写入位置0xCDCDCDCD。",当我尝试将文件中的值放入数组时。

谢谢!

#include <stdio.h>
#include <stdlib.h>



void read_vectors(int **v1,int **v2,int *m,int *n)
{
    FILE *fd;
    int i;
    fopen_s(&fd,"input.txt","r");
    if(fd==NULL)
    {
        perror("Error at opening the file.\n");
        exit(2);
    }
    if(fscanf_s(fd,"%d %d",m,n)!=2)
    {
        perror("Error at reading the sizes of the arrays.");
        exit(2);
    }
    if((*v1=(int*)malloc(sizeof(int)*(*m)))==NULL)
    {
        perror("Error at allocating memory.\n");
        exit(2);
    }
    if((*v2=(int*)malloc(sizeof(int)*(*n)))==NULL)
    {
        perror("Error at allocating memory.\n");
        exit(2);
    }
    for(i=0;i<*m;i++)
    {
        if(fscanf_s(fd,"%d ",v1[i])!=1)
        {
            perror("Error at reading the numbers.\n");
            exit(2);
        }
    }
    for(i=0;i<*n;i++)
    {
        if(fscanf_s(fd,"%d ",v2[i])!=1)
        {
            perror("Error at reading the numbers.\n");
            exit(2);
        }
    }
    fclose(fd);
}

void print_vector(int*v,int n)
{
    int i;
    printf("The content of the vector of size:%d is:\n",n);
    for(i=0;i<n;i++)
    {
        printf("%d ",v[i]);
    }
    printf("\n");
}

int main(int argc,char*argv[])
{
    int *v1,*v2,m,n;
    read_vectors(&v1,&v2,&m,&n);
    print_vector(v1,m);
    print_vector(v2,n);

    return 0;
}

0 个答案:

没有答案