简体   繁体   English

C ++指针和变量分配

[英]C++ Pointers and Variable Assignment

So, I am facing a very very unusual problem with my program. 因此,我的程序面临非常非常不寻常的问题。 Here is my program 这是我的程序

    void insertItem (Song *&, Song *&, char ar [], int);
    void printList (Song *);
    void deleteList (Song *&, Song *&);
    void processList (Song *&);

    int main (int argc, char * argv[]) {    
    char * filename = argv[1]; char line [31];


int m, n, a;
------------


    /*
        Head and tail pointer to maintain a list of songs
    */
    Song *head;
    Song *tail;

    if (filename == NULL)
        exit(1);    

    fstream fio;
    fio.open (filename, ios::in);



**fio >> m; fio >> n;**
-----------------------


    // Reading the file
    while (!fio.eof()){


**fio >> a;**
-------------

        fio >> line;


**insertItem (head, tail, line, a);**
-------------------------------------

    }
    fio.close();

    printList (head);



**for (int b = 0; b < n; ++b) processList (head);**
---------------------------------------------------


    cout << "\nDeleting List";
    deleteList (head, tail);
    return 0;
    }

I declare 3 static variables (m,n, and a) and I use all three of them. 我声明了3个静态变量(m,n和a),并且使用了这三个变量。 The problem I am facing is that as soon as try to initialize a variable b in the for loop, I get a segmentation fault. 我面临的问题是,一旦尝试在for循环中初始化变量b ,我就会遇到分段错误。 I debugged it using gdb and the value of the head pointer changes when I try to use the variable b in the for loop. 我使用gdb调试了它,当我尝试在for循环中使用变量b时,head指针的值发生了变化。 On the contrary, if I use a previously used variable like m or a instead of making a new variable for the for loop, it runs absolutely fine. 相反,如果我使用以前使用的变量(例如m或a)而不是为for循环创建新变量,则它运行得很好。 The address of the head pointer doesn't change. 头指针的地址不变。 Any clue on what might be happening here? 关于这里可能发生什么的任何线索?

There are at least two errors in your code: you never initialize head and tail (so anything you do with them is undefined behavior), and you don't check that your input has succeeded before using it. 您的代码中至少有两个错误:您永远不会初始化headtail (因此,使用它们进行的任何操作都是未定义的行为),并且在使用之前,请不要检查输入是否成功。 (Your first loop should probably be while ( fio >> line ) . But you don't want to use m or n either, unless you've checked that the input succeeded.) (您的第一个循环可能应该是while ( fio >> line ) 。但是除非您已检查输入是否成功,否则您都不希望使用mn 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM