【问题标题】:Segmentation fault using scanf() [closed]使用 scanf() 的分段错误 [关闭]
【发布时间】:2018-10-24 15:32:07
【问题描述】:

下面的代码编译得很好,但是当我使用它时返回分段错误。

我在其他主题中搜索了一些类似的错误,但我没有找到太多。

以防万一,感谢您的帮助。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double main( char *argv[]){
        FILE *ifp;
        double e,e_a,e_b,a,ct,b,sigma,tol;
        double Cla, theta;
        int n, nmax;

        ifp=fopen(argv[0],"r");
        scanf(ifp,"%lf %lf\n",&theta,&Cla);

        a=0.002;
        b=0.1;
        nmax=1000;
        ct=(a+b)/2;
        tol=0.00000001;

        sigma=0.14066;
        e_a=theta-(a*6/(sigma*Cla)+3/2*sqrt(a/2));
        e_b=theta-(b*6/(sigma*Cla)+3/2*sqrt(b/2));
        n=0;
}

【问题讨论】:

    标签: c pointers scanf point


    【解决方案1】:

    这里有三个问题。首先

    scanf(ifp,"%lf %lf\n",&theta,&Cla);
    

    当你看起来想使用fscanf时,你正在调用scanf

    fscanf(ifp,"%lf %lf\n",&theta,&Cla);
    

    其次是你打开的文件:

    ifp=fopen(argv[0],"r");
    

    argv[0] 是正在运行的可执行文件的名称,这可能不是您想要的。如果要传入第一个参数,请使用argv[1]

    ifp=fopen(argv[1],"r");
    

    最后是main的定义:

    double main( char *argv[]){
    

    这不是一个有效的定义,因为它应该返回一个 int 并且同时具有 argcargv 或两者都没有:

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

    您还应该检查是否传递了参数:

    if (argc < 2) {
        printf("missing argument\n");
        exit(1);
    }
    

    【讨论】:

    • 已解决。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    相关资源
    最近更新 更多