【问题标题】:Segmentation fault 11, issue using pointers and returning them分段错误 11,使用指针发出并返回它们
【发布时间】:2018-03-18 01:22:08
【问题描述】:

运行此程序时,我不断收到分段错误。我正在尝试读取文件(插入命令行),并将每个文件中的 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;
}

【问题讨论】:

  • 我总是使用Valgrind 来找出为什么会出现段错误。使用-g 编译并使用valgrind &lt;program&gt; 运行。祝你好运!
  • 您是在 64 位系统中执行此操作吗?请记住,int 通常仍然是 32 位,而指针是 64 位。现在再想想如果你切掉指针的前 32 位并从函数中返回该值会发生什么。并打开警告(如果编译器尚未向您发出警告)!
  • calc 函数中,变量answer 未初始化。而且您不会测试fopen 是否返回NULL,如果由于某种原因无法打开文件,则会发生这种情况。 readPoints 返回一个 int 但它应该返回一个 POINTS*
  • 简短回答:了解如何使用调试器。
  • 编译器警告是你的朋友。打开所有警告。为什么?因为如果编写您用来将代码转换为可运行可执行文件的编译器的人认为您的代码正在做的事情太糟糕了,他们会花时间并努力告诉您这是一个坏主意,您可能应该听他们说。这是一种冗长的说法,即“编译器认为您的代码可能很愚蠢和/或危险,即使它不违反语言标准。”它可能是正确的。

标签: c pointers struct segmentation-fault return


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多