Michael Metreveli
Michael Metreveli

Reputation: 111

I can't understand why this program keeps crashing

this program keeps crashing instead of letting me input arguments, why?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char* argv[]) {
    int shift = atoi(argv[1]);
    char message[256];
    strcpy(message, argv[2]);
    int i;

    for (i = 0; i < strlen(message); i++) {
        printf("%c", message[i] + shift);
    }
    putchar('\n');

    return 0;
}

I am using codeblocks. But I also tried to run it with Notepad++. After I compiled it and when I run it it simply crashes: Name.exe has stopped working. Shouldn't it ask me to input arguments on command line?

Upvotes: 1

Views: 237

Answers (1)

Idan Arye
Idan Arye

Reputation: 12603

A program can't possibly crash before you enter the arguments, because you need to enter the arguments before the program starts.

That is: you don't run your program like this:

Program.exe
12
hello

you need to run it like this:

Program.exe 12 hello

If you are using an IDE(you probably do), you need to configure your IDE to add the arguments. How to do that depends on which IDE you use. I assume you use Visual Studio - here is how to do it in Visual Studio: https://stackoverflow.com/a/3697320/794380

Upvotes: 7

Related Questions