From 03b9bb9ab2cc1859267413d5d2fadd6a843f68c6 Mon Sep 17 00:00:00 2001 From: Trygve Date: Mon, 26 Feb 2024 13:11:04 +0100 Subject: [PATCH] start lab 2 --- lab_2/8_wildptr-fixed.cpp | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 lab_2/8_wildptr-fixed.cpp diff --git a/lab_2/8_wildptr-fixed.cpp b/lab_2/8_wildptr-fixed.cpp new file mode 100644 index 0000000..d060b1c --- /dev/null +++ b/lab_2/8_wildptr-fixed.cpp @@ -0,0 +1,41 @@ +#include +#include +#include + +void crop(int num_strings, char** strings, int characters_cropped); + +int main(int argc, char** argv) +{ + /* crop the first two letters of each input argument, + * by jumping from index 0 to index 2 + */ + int jump_to_index = 2; + + /* crop all of the strings in argv, except the one with index 0; + * note that argv[0] is always the program's name. + * only the argv[i] with i > 0 are genuine command-line arguments. + */ + crop(argc-1, argv+1, jump_to_index); + + for(int i = 1; i < argc; i++) + std::cout << "Argument no. " << i + << " was cropped to \"" << argv[i] << "\".\n"; +} + +/* implementation that "crops" a string by incrementing it, so that + * it effectively begins characters further ahead. + */ +void crop(int num_strings, char** strings, int characters_cropped) +{ + assert(characters_cropped >= 0); + + for(int i = 0; i < num_strings; i++) + if(strlen(strings[i]) >= characters_cropped) + strings[i] += characters_cropped; + else strings[i] += strlen(strings[i]); +} + +/* make and try executing: + * ./wildptr-fixed ABCDE FGHIJ KLMNO + * ./wildptr-fixed ABCDE FGHI JKL MN O + */