Recall & Review
beginner
What are
argc and argv in a C program's main function?argc is the count of command-line arguments passed to the program, including the program name itself. argv is an array of strings (character pointers) holding each argument.Click to reveal answer
beginner
How do you access the first command-line argument (not the program name) in C?
You access it using
argv[1]. argv[0] is the program name, so the first user argument is at index 1.Click to reveal answer
intermediate
What happens if you try to access
argv elements beyond argc - 1?Accessing beyond
argc - 1 leads to undefined behavior because those elements do not exist. It can cause crashes or garbage data.Click to reveal answer
beginner
How can you convert a command-line argument string to an integer in C?
Use the
atoi() function from stdlib.h. For example, int x = atoi(argv[1]); converts the first argument to an integer.Click to reveal answer
beginner
Why is it important to check
argc before accessing argv elements?Because if you access
argv elements without checking argc, you might read invalid memory if the argument was not provided, causing errors.Click to reveal answer
What does
argc represent in a C program?✗ Incorrect
argc counts how many arguments were passed, including the program name.How do you access the program's name from the arguments?
✗ Incorrect
The program name is stored at
argv[0].Which header file is needed to use
atoi()?✗ Incorrect
atoi() is declared in stdlib.h.What is the risk of accessing
argv[3] when argc is 2?✗ Incorrect
Accessing beyond
argc - 1 is unsafe and can cause crashes.If you want to print all command-line arguments, which loop is correct?
✗ Incorrect
Looping from 0 to
argc - 1 prints all arguments including program name.Explain how to safely access command-line arguments in a C program.
Think about how to avoid accessing invalid memory.
You got /4 concepts.
Describe the role of
argv[0] and how it differs from other arguments.What does the first element in argv usually hold?
You got /3 concepts.