我寫了一個函數,用於確定是否分配默認值(如果標記不存在,則分配默認值,如果標記存在,則分配用戶通過的值)。我試圖用一個字符串來測試我的函數,看它是否給我提供了正確的數字。當我嘗試運行測試並編譯時,我總是收到「Segmentation Fault」(分段錯誤),但測試不起作用。 :(當我嘗試運行測試時,爲什麼會出現「分段錯誤」錯誤?
這是我的頭文件:
#ifndef COMMANDLINE_H
#define COMMANDLINE_H
#include "data.h"
#include <stdio.h>
struct point eye;
/* The variable listed above is a global variable */
void eye_flag(int arg_list, char *array[]);
#endif
下面是我實現文件:
#include <stdio.h>
#include "commandline.h"
#include "data.h"
#include "string.h"
/* Used global variables for struct point eye */
void eye_flag(int arg_list, char *array[])
{
eye.x = 0.0;
eye.y = 0.0;
eye.z = -14.0;
/* The values listed above for struct point eye are the default values. */
for (int i = 0; i <= arg_list; i++)
{
if (strcmp(array[i], "-eye") == 0)
{
sscanf(array[i+1], "%lf", &eye.x);
sscanf(array[i+2], "%lf", &eye.y);
sscanf(array[i+3], "%lf", &eye.z);
}
}
}
這裏是我的測試案例:
#include "commandline.h"
#include "checkit.h"
#include <stdio.h>
void eye_tests(void)
{
char *arg_eye[6] = {"a.out", "sphere.in.txt", "-eye", "2.4", "3.5", "6.7"};
eye_flag(6, arg_eye);
checkit_double(eye.x, 2.4);
checkit_double(eye.y, 3.5);
checkit_double(eye.z, 6.7);
char *arg_eye2[2] = {"a.out", "sphere.in.txt"};
eye_flag(2, arg_eye2);
checkit_double(eye.x, 0.0);
checkit_double(eye.y, 0.0);
checkit_double(eye.z, -14.0);
}
int main()
{
eye_tests();
return 0;
}
根據我糟糕的技能':)','分段錯誤'發生在某些事情(循環)試圖訪問某些事物時「'不存在'」......在你的情況下,t數組[6],儘管最後一個元素是數組[5]。 – yulian