0
0
Cprogramming~5 mins

Accessing arguments - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AArray of command-line arguments
BNumber of command-line arguments including program name
CPointer to the first argument
DLength of the first argument string
How do you access the program's name from the arguments?
Aargv[0]
Bargc
Cargv[1]
Dargv[argc]
Which header file is needed to use atoi()?
A<string.h>
B<stdio.h>
C<stdlib.h>
D<ctype.h>
What is the risk of accessing argv[3] when argc is 2?
ANo risk, safe to access
BReturns empty string
CReturns NULL safely
DUndefined behavior, may crash
If you want to print all command-line arguments, which loop is correct?
Afor (int i = 0; i < argc; i++) printf("%s\n", argv[i]);
Bfor (int i = 1; i <= argc; i++) printf("%s\n", argv[i]);
Cfor (int i = 0; i <= argc; i++) printf("%s\n", argv[i]);
Dfor (int i = 1; i < argc; i++) printf("%s\n", argv[i]);
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.