c - 段错误 11,使用指针并返回它们的问题

标签 c pointers struct segmentation-fault return

运行该程序时,我不断遇到段错误。我正在尝试读取文件(插入到命令行中),并将每个文件中的 x 和 y 坐标分配给名为 POINTS 的动态分配的内存结构(使用名为 readPoints 的函数)。将它们保存到这些结构中后,我将它们传递给函数调用 calc,其中 x 和 y 值相乘,然后添加到下一个 x 和 y 相乘......依此类推。有人可以向我解释一下我错在哪里吗!我不擅长指点。 预先感谢您。

#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;
}

最佳答案

readpoints 函数应将其第一个参数作为文件指针 BCS fopen 返回 FILE 指针,但您正在使用 char 指针。 fscanf 第一个参数应该是文件指针。请指正

关于c - 段错误 11,使用指针并返回它们的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46602298/

上一篇:c - C 音译字母

下一篇:C 请求数组

相关文章:

c - 将结构传递给函数并在 C 中修改它

代码在 Xcode 中不工作,但在 NetBeans 中工作正常?

C++ 无法在单独函数中的变量之间建立通信

当数据复制/扫描/读取到未初始化的指针时崩溃或 "segmentation fault"

c# - 结构数组返回错误

c++ - 我无法理解 C++ 中的结构声明

c - 与 '%rbx' 后缀一起使用的寄存器 0x​​104567910 不正确

c - 线程C段错误一个简单的程序

c - 找到最长的子序列的长度,其中包含多个连续的 k 个 0,然后是多个连续的 k 个 1

c++ - 指向基类的指针 vector ,调用虚函数的奇怪行为