Salta al contenuto
Note per Studenti Command-Line Arguments and Structs Report

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:

c
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 index argc.
  • argv[0] is the name by which the program was invoked, so argc >= 1; argc == 1 means no arguments after the name.
  • Modifying the argv strings is allowed but discouraged for portability.
bash
./myprogram arg1 arg2 arg3

Here argv[0] is myprogram, argv[1] is arg1, and so on; the second argument is char *secondArg = argv[1];.

c
for (int i = 1; i < argc; i++)
    printf("%s\t", argv[i]);

C++ example printing everything:

cpp
#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>):

c
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;
}
  • atoi stops at the first non-numeric character and returns the value so far: error-prone with complex input; no error reporting (the same holds for atol).
  • strtol gives more control: error handling and different bases (10, 16, ...).
c
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): errno is zero, endptr differs from the input, and *endptr is '\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>; prototype int 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 -c without arguments; "a:b": -a requires an argument (-a value or -avalue), -b does not. Unknown options return ?; -1 ends the options.
c
#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 --verbose and --count=5 alongside short ones, via an array of struct option giving name, whether an argument is needed and the short-option mapping.
  • Slide exercises: testEcho (print each argument with its index); testSum (sum integer arguments with strtol and endptr, 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, printing Hello, <name>! N times (defaults name "world", verbose 0, N 1; use getopt() / getopt_long() or strncmp / strcmp with strstr or 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.

c
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:

c
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}; for struct Student { int studentID; char name[50]; int age; }.
  • Member access: . on a struct variable, -> on a pointer to struct.
c
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):
c
void displayStudent(struct Student s) {
    printf("ID: %d, Name: %s, Age: %d\n", s.studentID, s.name, s.age);
}

typedef

Gives alias names to types; combined with struct it improves readability:

c
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.

c
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)
  • typedef works 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[]): argc counts the program name too, so argc >= 1; argv[0] is the invoked name and argv[argc] is NULL. Every argument is a string.
c
for (int i = 1; i < argc; i++) printf("%s\t", argv[i]);
struct union
Memory one block per member one shared block
Values all held at once one valid value at a time

Teoria collegata