WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

C Β· Intermediate Β· question 25 of 100

What is the use of command line arguments in C? How can they be accessed in the main() function?

πŸ“• Buy this interview preparation book: 100 C questions & answers β€” PDF + EPUB for $5

Command line arguments are inputs that are passed to a program at the time it is run from the command line. They allow the user to specify certain options or parameters to the program without having to modify the source code or recompile the program.

In C programming language, command line arguments can be accessed within the main() function using the argc and argv parameters. The argc parameter contains the number of command line arguments passed to the program, and the argv parameter is an array of strings containing the actual arguments.

Here is an example of how to access command line arguments in the main() function:

    int main(int argc, char *argv[]) {
        printf("Number of command line arguments: %dn", argc);
        
        for (int i = 0; i < argc; i++) {
            printf("Argument %d: %sn", i, argv[i]);
        }
        
        return 0;
    }

In this example, the main() function takes two parameters: argc and argv. The printf() function is used to print the number of command line arguments (argc) and the value of each argument (argv[i]) using a for loop.

For example, if this program is run with the command ./program arg1 arg2 arg3, the output would be:

    Number of command line arguments: 4
    Argument 0: ./program
    Argument 1: arg1
    Argument 2: arg2
    Argument 3: arg3

In this example, the argv array contains four elements, with the first element being the name of the program itself (./program) and the remaining elements being the actual command line arguments (arg1, arg2, and arg3).

Command line arguments can be used for a variety of purposes, such as specifying input and output files, setting program options, and providing additional information to the program. They can make programs more flexible and easier to use by allowing users to customize their behavior without having to modify the source code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C interview β€” then scores it.
πŸ“ž Practice C β€” free 15 min
πŸ“• Buy this interview preparation book: 100 C questions & answers β€” PDF + EPUB for $5

All 100 C questions Β· All topics