Good day to all. There is such a problem: when transferring parameters to the Linux console, the error "Segmentation error (memory dump made)" is displayed. Here is the program code (you need to display the required Fibonacci number by index):

int main(int argc, char* argv[]) { cout << "Your value is "; for (int i = 0; argc; i++){ int a = atoi(argv[i]); if (a <= 2) cout << "1"; else{ int x = 1; int y = 0; int ansver; for (int j = 1; j <= a; j++) { ansver = x + y; x = y; y = ansver; } cout << ansver; } } return 0; } 

    2 answers 2

    And how many times the cycle will be executed

     for (int i = 0; argc; i++) 

    If argc always greater than zero? ...

    And yet - argv[0] is just the name of the program itself (as a rule), but never - not a command line argument.

    In a word, here:

     int main(int argc, char* argv[]) { cout << "Your value is "; for (int i = 1; i < argc; i++){ int a = atoi(argv[i]); if (a <= 2) cout << "1 "; else { int x = 1; int y = 0; int answer; for (int j = 1; j <= a; j++) { ansver = x + y; x = y; y = answer; } cout << answer << " "; } } return 0; } 
    • it turned out, thanks! And if I need to connect this program with another .cpp file, in which I set new keys with the functions I need, how can I do this, do not tell me? - Kyrlik
    • Didn't quite understand what you want to ask ... - Harry
    • for example: "ls -aR", but instead of -aR I prescribe a new key (say -z) and give it the function I need. If I try to combine my mini-program and the file with the prescribed new keys, I write "the plural definition of main". If you try to merge two data files (ie, stupidly insert the necessary code into my program and forget about the problem), then, in my opinion, it will be wrong - Kyrlik
    • I still do not understand. So I will speak out theoretically - design this code for Fibonacci numbers as a separate function. main should deal only with parsing the command line and calling the relevant functions (and, of course, it should be one in the program). - Harry
    • I would add that parsing the string should be structured. Look at the sources of linux utilities, there is a good parsing pattern. After writing once, then you only need to add pointers to the processing functions in the array - Swift

    So what is this cycle

     for (int i = 0; argc; i++) 

    This is an endless loop. It is not surprising that at some point access to argv[i] crashes, given that argv[argc] always equal to the null pointer. Maybe meant

     for (int i = 0; i < argc; i++) 

    ?