Command-Line Arguments and Structs
Command-line arguments
Information given to the program when it is run (configuration, input files, debugging flags, ...), useful to parameterize programs without changing the source. In C/C++ they arrive as parameters of main:
int main(int argc, char *argv[]); // the other standard form is int main(void)argc(argument count): number of arguments including the program name.argv(argument vector): array of null-terminated strings, one per argument; the array ends with a null pointer at indexargc.argv[0]is the name by which the program was invoked, soargc >= 1;argc == 1means no arguments after the name.- Modifying the argv strings is allowed but discouraged for portability.
./myprogram arg1 arg2 arg3Here argv[0] is myprogram, argv[1] is arg1, and so on; the second argument is char *secondArg = argv[1];.
for (int i = 1; i < argc; i++)
printf("%s\t", argv[i]);C++ example printing everything:
#include <iostream>
int main(int argc, char *argv[]) {
std::cout << "Number of arguments: " << argc << std::endl;
for (int i = 0; i < argc; i++) {
std::cout << "Argument " << i << ": " << argv[i] << std::endl;
}
return 0;
}Run ./my_program arg1 arg2 arg3: Number of arguments: 4, then Argument 0: ./my_program ... Argument 3: arg3.
Always check that the expected number of arguments is given and handle invalid or missing ones gracefully.
Converting strings to numbers
Arguments are strings. atoi (header <stdlib.h>; C++ std::atoi in <cstdlib>):
int atoi(const char *str); // returns 0 if the string cannot be converted
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
int num = atoi(argv[1]); // first argument as integer
printf("String: %s, Integer: %d\n", argv[1], num);
}
return 0;
}atoistops at the first non-numeric character and returns the value so far: error-prone with complex input; no error reporting (the same holds foratol).strtolgives more control: error handling and different bases (10, 16, ...).
long int strtol(const char *str, char **endptr, int base);
// str: string; endptr: set to the first non-converted character; base: e.g. 10 or 16
char str[] = "123abc";
char *endptr;
long int num = strtol(str, &endptr, 10);
printf("Converted number: %ld\n", num); // 123
printf("Non-numeric part: %s\n", endptr); // abc- Robust check pattern (also
strtoul):errnois zero,endptrdiffers from the input, and*endptris'\0'(whole string converted). Needs<errno.h>.
Manual option parsing
Recognize options starting with -, -- as end of options, match names with strcmp / strncmp and extract values; validate carefully and support positional arguments.
getopt
getopt parses options like -a -b value -c, supports grouping (-abc) and option arguments (-o output.txt).
- Header
<unistd.h>; prototypeint getopt(int argc, char * const argv[], const char *optstring); - Globals:
char *optarg(argument of the current option),int optind(index of the next argv element: the "rest" arguments start here),int optopt(option that caused an error),int opterr(1 = automatic error messages, 0 = off). - optstring:
"abc"accepts-a -b -cwithout arguments;"a:b":-arequires an argument (-a valueor-avalue),-bdoes not. Unknown options return?;-1ends the options.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // getopt
int main(int argc, char *argv[]) {
int opt;
int aflag = 0;
char *bvalue = NULL;
int ccount = 0;
// "a:bc": -a needs an argument, b and c do not.
while ((opt = getopt(argc, argv, "a:bc")) != -1) {
switch (opt) {
case 'a':
bvalue = optarg; // argument to -a
break;
case 'b':
aflag = 1; // -b seen
break;
case 'c':
ccount++; // -c (can be repeated if grouped)
break;
case '?': // unknown option or missing arg
return 2; // getopt already printed an error unless opterr == 0
default: /* shouldn't happen */
return 2;
}
}
printf("aflag(-b)=%d, aarg(-a)=%s, ccount=%d\n",
aflag, bvalue ? bvalue : "(none)", ccount);
// Non-option arguments start at argv[optind]
for (int i = optind; i < argc; i++) {
printf("positional: %s\n", argv[i]);
}
return 0;
}The listing is split over two slides, with the variable names aflag / bvalue swapped relative to the options they hold (as in the slide).
getopt_long(GNU, not standard C, can be included conditionally): long options such as--verboseand--count=5alongside short ones, via an array ofstruct optiongiving name, whether an argument is needed and the short-option mapping.- Slide exercises:
testEcho(print each argument with its index);testSum(sum integer arguments withstrtolandendptr, error and non-zero exit on a non-integer, sum 0 if none; headers<stdio.h>,<stdlib.h>,<errno.h>); flag parser with-n <name>,-v,--repeat=<N>,-h, printingHello, <name>!N times (defaults name "world", verbose 0, N 1; usegetopt()/getopt_long()orstrncmp/strcmpwithstrstror manual parse for--repeat=).
struct
A structure is a derived type built from members of other types (int, float, char, arrays, other structs, unions). Defining it reserves no memory: it creates a new type.
struct student {
char surname[20];
char name[20];
unsigned int id;
unsigned int birthYear;
char gender;
};
struct student std1, std2; // variables declared like any other type
// or: struct student { ... } std1, std2;Another example, with nesting:
struct point { int x; int y; };
struct rectangle { struct point highLeft; struct point lowRight; };
struct Date { int day; int month; int year; };
struct Employee { int empID; char empName[50]; struct Date hireDate; };- Initialization:
struct Student student2 = {101, "John Doe", 20};forstruct Student { int studentID; char name[50]; int age; }. - Member access:
.on a struct variable,->on a pointer to struct.
student1.studentID = 102;
strcpy(student1.name, "Jane Smith");
student1.age = 21;
struct Student *p = &student1;
p->studentID = 102;
printf("%s\t%s\n", std1.name, std1.surname);
printf("%s\t%s\n", stdPtr->name, stdPtr->surname); // stdPtr = &std1- Passing to functions: by value or by pointer (pointer when the function must modify it):
void displayStudent(struct Student s) {
printf("ID: %d, Name: %s, Age: %d\n", s.studentID, s.name, s.age);
}- Size: roughly the sum of the member sizes, but padding may be added to align members; use
sizeof. - Uses: records (students, employees, products), linked lists (Liste concatenateLista concatenata semplice: nodi allocati dinamicamente collegati da puntatori; inserimento e rimozione in testa, scorrimento, ricerca, inserimento ordinato, deallocazione; confronto dei costi con l'array; versione in Python.Liste concatenate →), serialization.
typedef
Gives alias names to types; combined with struct it improves readability:
typedef struct { int x; int y; } Point;
typedef unsigned char Byte;typedef vs #define: both create aliases, but typedef only for types and is processed by the compiler; #define is more general (it can alias values) and is processed by the preprocessor (Compilation, Linking and ExecutionHow a C source file becomes a running program: editing, preprocessing, compiling, linking, plus interpreters versus compilers and static versus dynamic linking.Compilation, Linking and Execution →).
sizeof
Unary operator giving the bytes needed for a type or variable (types differ by architecture: int may use 2 or 4 bytes): sizeof(int) is 4; char name[20]; sizeof(name) is 20.
union
Like a struct but all members share the same memory: only one member is valid at a time (writing one overwrites the others). Size = size of the largest member.
union CarInfo {
int carID;
float price;
char owner[50];
};
union CarInfo car1;
union CarInfo car2 = {101}; // initializes the first member, carID
car1.carID = 102; // carID active
printf("Car ID: %d\n", car1.carID);
car1.price = 25000.50; // now price is active
printf("Car Price: %.2f\n", car1.price);| struct | union | |
|---|---|---|
| Memory | separate space per member | one shared block |
| Values | all members held at once | one valid value at a time |
struct number { int x; double y; } |
4 + 8 = 12 bytes (slide figure, without padding) | 8 bytes (union number, same members) |
typedefworks for unions too. Use a union to save memory when only one of several types is active at a time (embedded and low-level code, hardware interfacing); use a struct to store several values simultaneously.- Pitfalls: reading an inactive member (undefined behavior), no type safety, one active member only, hard to debug.
- Slide exercises: define
struct Point { int x, y; }, initialize it in two ways, print p1 and p2 as (x,y), compute the Manhattan distance |x1-x2| + |y1-y2|; array of 3 points initialized (1,2), (3,4), (5,6) and integer centroid (avg_x, avg_y) with integer division.
Versione ripasso
int main(int argc, char *argv[]):argccounts the program name too, soargc >= 1;argv[0]is the invoked name andargv[argc]is NULL. Every argument is a string.
for (int i = 1; i < argc; i++) printf("%s\t", argv[i]);./prog arg1 arg2: hereargc == 3andargv[1]isarg1. Check the count before readingargv[k]. Running./my_program arg1 arg2 arg3printsNumber of arguments: 4, thenArgument 0: ./my_programthroughArgument 3: arg3.- Slide exercise
testSum: add the integer arguments withstrtolandendptr; a non-integer gives an error and a non-zero exit, and no arguments give sum 0 (headers<stdio.h>,<stdlib.h>,<errno.h>). atoi(str)returns 0 on failure, stops at the first bad character and reports no error. Usestrtol(str, &endptr, base): the conversion is whole whenerrno == 0,endptr != strand*endptr == '\0'(needs<errno.h>). With"123abc"it gives 123 andendptrpoints toabc.getopt(argc, argv, "a:bc")inwhile ((opt = getopt(...)) != -1)with aswitch:optargis the option argument,optindthe first positional argument,?an unknown option or a missing argument. A colon after a letter means the option takes a value.getopt_long(GNU) adds--longoptions throughstruct option.struct student { ... };creates a type and reserves no memory. Members via.on the variable, via->on a pointer. Structs can nest (struct rectangle { struct point highLeft; ... }). Initialize with{101, "John Doe", 20}.sizeofon a struct can exceed the sum of the members because of padding: always usesizeof, never add the members by hand.- Pass a struct by value (a copy: the function cannot change the caller's one) or by pointer (to modify it) (Functions, Variables and ScopeHow to declare variables, define and call functions with prototypes and return values, pass arguments by value or through pointers, and use function pointers.Functions, Variables and Scope →).
typedef struct { int x; int y; } Point;is handled by the compiler;#defineby the preprocessor, which can alias values too (Compilation, Linking and ExecutionHow a C source file becomes a running program: editing, preprocessing, compiling, linking, plus interpreters versus compilers and static versus dynamic linking.Compilation, Linking and Execution →).union: all members share one block, its size is the largest member, only one member is valid at a time: writingpriceoverwritescarID.
| struct | union | |
|---|---|---|
| Memory | one block per member | one shared block |
| Values | all held at once | one valid value at a time |
- Lists of structs: Liste concatenateLista concatenata semplice: nodi allocati dinamicamente collegati da puntatori; inserimento e rimozione in testa, scorrimento, ricerca, inserimento ordinato, deallocazione; confronto dei costi con l'array; versione in Python.Liste concatenate →.
- Typical errors: assuming
argcexcludes the program name,atoion untrusted input, reading an inactive union member, forgetting padding when computing sizes.