首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >分段故障11,使用指针并返回它们

分段故障11,使用指针并返回它们
EN

Stack Overflow用户
提问于 2017-10-06 17:12:02
回答 1查看 91关注 0票数 0

当我运行这个程序时,我一直得到一个分段错误。我尝试读取文件(插入到命令行中),并将每个文件中的x和y坐标分配给一个动态分配的内存结构POINTS (使用名为readPoints的函数)。在将它们保存到这些结构中之后,我将它们传递给函数调用calc,其中x和y值相乘,然后相加到下一个x和y相乘的值上。等等。有人能给我解释一下我哪里出错了吗?我不擅长指点。提前谢谢你。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

typedef struct
{   
    float xcord;
    float ycord; 
}POINTS;

int readPoints(char* file, int numofpoints);
int calc(POINTS* points, int numofpoints);

int main(int argc, char* argv[])
{   

int numoffiles;
FILE* file; 
int result, i;
numoffiles = argc;

POINTS* pointer;
int numofpoints;

if(numoffiles == 1)
{   
    printf("Please enter a file\n");
}

for(i=1; i<numoffiles; i++)
{   
    file = fopen(argv[i], "r");
    fscanf(file, "%d", &numofpoints);
    pointer = readPoints(file, numofpoints);

    if( pointer == NULL)
    {   
        printf("Error return from readPoints function");
    }


    result = calc(&pointer[i], numoffiles);


    printf("%12f", result);
    free(pointer);
}
}

int readPoints(char* file,int numofpoints)
{
    int i, j;

    POINTS* Pointstructs;
    Pointstructs = (POINTS*)malloc((numofpoints)*sizeof(POINTS));

    if(file == NULL)
    {
        printf("Error transferring file into readPoints\n");
    }

    for(i=0; i<numofpoints; i++)
    {
        fscanf(*file, "%f, %f", &Pointstructs[i].xcord, &Pointstructs[i].ycord);
        printf("%f, %f", Pointstructs[i].xcord, Pointstructs[i].ycord);
    }

    return Pointstructs;
}

int calc(POINTS* points, int numofpoints)
{
    int i=0, j=0;
    int answer;

    while(i<numofpoints && j<numofpoints)
    {
        answer += points[i].xcord * points[j].ycord;
        i++;
        j++;
    }    
return answer;
}
EN

回答 1

Stack Overflow用户

发布于 2017-10-07 00:05:59

readpoints函数应该把它的第一个参数作为文件指针,BCS fopen返回文件指针,但是你使用的是char指针。fscanf第一个参数应该是文件指针。请改正

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46602298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档