Argv Parameter Access
Understanding argv Array Structure
In C, argv
is an array of character pointers (strings) representing command-line arguments. Each element is a null-terminated string.
graph LR
A[argv[0]] --> B[Program Name]
A --> C[First Actual Argument]
D[argv[1]] --> C
E[argv[2]] --> F[Second Actual Argument]
Basic Argument Accessing Techniques
Direct Index Access
#include <stdio.h>
int main(int argc, char *argv[]) {
// Accessing first argument
if (argc > 1) {
printf("First argument: %s\n", argv[1]);
}
// Accessing specific arguments
if (argc > 2) {
printf("Second argument: %s\n", argv[2]);
}
return 0;
}
Iterative Argument Processing
#include <stdio.h>
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Argument Type Conversion
Conversion Method |
Description |
Example |
atoi() |
Convert string to integer |
int value = atoi(argv[1]); |
atof() |
Convert string to float |
float num = atof(argv[1]); |
strtol() |
Convert string to long integer |
long val = strtol(argv[1], NULL, 10); |
Advanced Argument Parsing
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
// Check minimum required arguments
if (argc < 3) {
fprintf(stderr, "Usage: %s <param1> <param2>\n", argv[0]);
exit(1);
}
// Safe integer conversion
int x = atoi(argv[1]);
int y = atoi(argv[2]);
printf("Processed arguments: %d, %d\n", x, y);
return 0;
}
Safety Considerations
- Always check
argc
before accessing argv
- Use bounds checking
- Validate argument types
- Handle potential conversion errors
Common Pitfalls
graph TD
A[Argument Access] --> B{Sufficient Arguments?}
B -->|No| C[Potential Segmentation Fault]
B -->|Yes| D[Safe Processing]
C --> E[Program Crash]
By mastering these techniques in the LabEx programming environment, developers can robustly handle command-line arguments in C programs.