0
運行此程序時,我不斷收到分段錯誤。我試圖讀取文件(插入到命令行中),並將每個文件中的x和y座標分配給名爲POINTS(使用稱爲readPoints的函數)的動態分配內存結構。在將它們保存到這些結構中之後,我將它們傳遞給函數調用calc,其中x和y值相乘,然後添加到下一個x和y相乘的上。有人可以向我解釋我出錯的地方!我不擅長指針。 預先感謝您。分段錯誤11,使用指針發出並返回它們
#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;
}
有多個地方你應該調用exit並停止執行程序。 – babon
我總是使用[Valgrind](https://www.valgrind.org)來找出爲什麼會出現段錯誤。使用'-g'編譯並運行'valgrind'。祝你好運! –
你在64位系統中執行此操作嗎?請記住,「int」通常仍然是32位,而指針是64位。現在再想一想,如果您切斷指針的前32位並從函數返回該值,會發生什麼情況。並打開警告(如果編譯器還沒有對你發出警告)! –