I dont understand a textbook question

I am learning C++ with the help of a book called C++ Crash Course by Josh Lospinoso. Chapter 3 is about Reference Types and it talks about the relation between arrays and pointers. The book presents this example:

1
2
3
4
5
6
7
8
9
10
11
int main() {
    char lower[] = "abc?e";
    char upper[] = "ABC?E";
    char* upper_ptr = upper;

    lower[3] = 'd';
    upper_ptr[3] = 'D'

    char letter_d = lower[3];
    char letter_D = upper_ptr[3];
}


A problem in the book asks me to: Add a read_from and a write_to function to Listing 3-6. These functions should read or write to upper or lower as appropriate. Perform bounds checking to prevent buffer overflows.

I am wondering if anyone has worked with this book. Can anyone just tell me what you think the are asking for?
1. Should the function detect whether the character to be added is an uppercase or lower case letter and add the letter to the corresponding string?
2. Should the function write to a specific index of the array?
3. Should the read function read the whole array or a single character?
4. Why am I having so much trouble understanding what they want from me here?

thanks to everyone.
its a poorly worded question. read and write could do anything at all, without more instructions.
the buffer overflow check, if you understand that part, is important. Its probably going on about C style strings, so it probably wants you to just read and write them as if strings. But who knows?

but this material looks dated. Consider putting this book down and using
learncpp.com as your material. It teaches you modern c++, including strings instead of char arrays (a C or 1990s era C++ way to do text strings) and saves pointers for later. If you work through their stuff in the order presented, you will be way ahead of the game.

edit: looking it up, maybe dated is the wrong, it seems to be c++17 compliant at least -- the issue is that it was apparently written with a bias towards C programmers. If you don't know C, it may have some odd ways of introducing things. On the bright side, it introduces boost, a very popular library system: much of what they do is ahead of what the C++ standard guys do. So the book may not be so bad, but consider the site there as a backup to help. If there are a lot of exercises, just skip this one since its unclear what they want, or read the next one, which may build on it and backwards explain what they needed.
Last edited on
That book's example looks more C than C++, not the best way to teach C++ for a beginner IMO. Especially if it is the 2nd edition published in 2019.

Yow, the price at Amazon is a bit steep! Used, new or eBook.
https://www.amazon.com/C-Crash-Course-Josh-Lospinoso/dp/1593278888/

There is an online free tutorial website for learning C++, Learn C++:
https://www.learncpp.com/

The lessons are more aligned with the C++ Core Guidelines in how C++ is presented:
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines

Amazon's webpage on the book has this to say:
Who Should Read This Book

This book is intended for intermediate to advanced programmers already familiar with basic programming concepts. If you don’t specifically have system programming experience, that’s okay. Experienced application programmers are welcome.

That kinda rules out this is a book for beginners.

Using just one book to learn C++ is not a good idea, the language is so huge a single book can't do justice to the language.

Books are outdated even the day they are published, C++ introduced C++20 shortly after this book was published, and C++23 is in the final stages of being approved.

There is a website, https://leanpub.com/, that sells eBooks as the authors are writing the book, at a price to reflect how complete the book is. And even when the book is finished if the author updates the material the updates are free. I've purchased several books from the company and nearly every book there's at least one update free of charge. A couple more than one.

I am a self-taught programming hobbyist, been doing it since the mid-1990's. Before the internet and online resources.

My programming library is several dozen books/eBooks, from C/C++ to WinAPI to game programming, etc.

This is one expensive hobby. :)
Why am I having so much trouble understanding what they want from me here?


it's not you - we all are having trouble understanding what they getting at.

I suspect they getting at the C++ container at member functions which does bounds checking (as opposed to [] which doesn't). So consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <cstring>
#include <exception>

char read_from(const char* str, size_t elem) {
	if (!str || elem >= std::strlen(str))
		throw std::out_of_range("element out of range");

	return str[elem];
}

void write_to(char* str, char ch, size_t elem) {
	if (!str || elem >= std::strlen(str))
		throw std::out_of_range("element out of range");

	str[elem] = ch;
}

int main() {
	char lower[] { "abc?e" };
	char upper[] { "ABC?E" };
	auto upper_ptr { upper };

	lower[3] = 'd';
	upper_ptr[3] = 'D';

	auto letter_d { lower[3] };
	auto letter_D { upper_ptr[3] };

	std::cout << letter_d << "  " << letter_D << '\n';

	try {
		write_to(lower, 'z', 1);
		std::cout << read_from(lower, 1) << '\n';
	}
	catch (const std::out_of_range& oor ) {
		std::cout << "Error - " << oor.what() << '\n';
	}

	try {
		write_to(upper, 'z', 11);
		std::cout << read_from(upper, 11) << '\n';
	}
	catch (const std::out_of_range& oor) {
		std::cout << "Error - " << oor.what() << '\n';
	}
}



d  D
z
Error - element out of range

Last edited on
I am learning C++ with ...

It doesn't sound like a great way to learn C++. It's really starting with C, which is hard, and is a distraction.

I can't recommend a different book, but I'm sure someone can. It's really important that you use a different book as making you learn C first isn't the way,
Last edited on
For a book on learning C++, my recommendation is:

Beginning C++20: From Novice To Professional by Ivor Horton
https://www.amazon.co.uk/Beginning-C-20-Novice-Professional/dp/1484258835/

@OP and anyone else trying to fathom this book.

Listing 3-6 is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cstdio>

int main()
{
    char lower[] = "abc?e";
    char upper[] = "ABC?E";
    
    char* upper_ptr = upper; // Equivalent: &upper[0]
    lower[3] = 'd'; // lower now contains a b c d e \0
    
    upper_ptr[3] = 'D'; // upper now contains A B C D E \0
    char letter_d = lower[3]; // letter_d equals 'd'
    
    char letter_D = upper_ptr[3]; // letter_D equals 'D'
    printf("lower: %s\nupper: %s", lower, upper);
    
    lower[7] = 'g'; // Super bad. You must never do this.
}


It's only chapter 3, so all is not lost on time spent so far. Take the advice you've already been given above and get a book that you can learn from. If you paid for the book, see if you can get your money back. :(

[EDIT: This code was so bad as a C++ learning exercise, I did see but ignored the pdf inclusions. However, for those stuck on seeing any merit in this book I have removed the chaff and made it a bit clearer with whitespace what is going on with the listing. It now shows even more starkly why the book is quite correctly dispensed with by @OP. Most of the code is irrelevant and confused rubbish, especially for such a simple job and simple concepts.

Ivor Horton is an excellent choice - even/especially older versions, say C11,C14 onwards of the book, are equally useful for novices.]


Last edited on
That listing shows the situation is even worse than I thought. Blatant C code "rewritten" for C++ by changing the header.

A quick and dirty rewrite in actual C++, if a bit sloppy and not optimized:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <memory>

int main()
{
   // char lower[] = "abc?e";
   std::string lower { "abc?e" };

   // char upper[] = "ABC?E";
   std::string upper { "ABC?E" };

   // added this here to show the original strings
   // printf("lower: %s\nupper: %s", lower, upper);
   std::cout << "lower: " << lower << "\nupper: " << upper << "\n\n";

   // char* upper_ptr = upper;
   char* upper_ptr { const_cast<char*> (upper.c_str()) };

   // another way is to use a unique_ptr....
   std::unique_ptr<std::string> upper_smt_prt { std::make_unique<std::string>(upper) };

   lower[3]     = 'd';
   upper_ptr[3] = 'D';

   char letter_d = lower[3];
   char letter_D = upper_ptr[3];

   std::cout << "lower: " << lower << "\nupper: " << upper << "\n\n";

   std::cout << upper_ptr << '\t' << *upper_smt_prt << '\n';

   // never ever do this, it will cause the universe to implode!
   // lower[7] = 'g';
}
lower: abc?e
upper: ABC?E

lower: abcde
upper: ABCDE

ABCDE   ABC?E


Kids, don't mangle C++ like this at home. :)

This book is not worth the money as a beginner's C++ book if the rest of it is like the code example againtry showed.
There is a couple of aspects of the book that make it semi-useful:

1. showing how to use 3rd party libraries by using Boost.

2. a chapter (10) about unit testing, using several different unit testing frameworks.

The exclusive use of C I/O in a book about learning C++ until the chapter about streams (16) is horrid IMO. Clearly the author believes C++ is "just a better C".

*SPIT*

@afduggirala, if you want to learn C++ that teaches better, modern methods consider a free tutorial website, Learn C++:
https://www.learncpp.com/

You won't learn all of what C++ has to offer. That is a HUUUUGE undertaking.

A decent C++ reference (and free) site:
https://en.cppreference.com/w/

Not designed to teach C++, though it has lots of intermediate to advanced level code snippets to try.

@againtry, your code snippet has several "copied from a PDF" markup artifacts, random letters after several statements. Copying the code as presented won't compile. :)

Yes, there is a github repository to get all the book's code: https://github.com/JLospinoso/ccc
Last edited on
Thanks to everyone for your responses.
I will take your advice and ditch this book. I will however provide a copy to my programming associate who is a C developer and has a lot more experience than I do.
I really appreciate all the resources provided, I knew about most of them.
I have gotten a hold of the "Beggining C++20" book recommended by seeplus, it looks A LOT more digestible. I have a physics background and will also use the book called "Discovering Modern C++" which provides a more "applied" context to C++ programming.

Thanks again, you have provided me with fresh air to continue my learning.
I will however now ask questions about any exercises contained in the 2 aforementioned books if I have any in the future.
@afduggirala, fair warning, there is currently only one compiler capable of properly using C++20 as used in the book seeplus suggested, Visual Studio 2019/2022.

The book's source code github (https://github.com/Apress/beginning-cpp20) has some, not all, examples and exercises that don't use modules. And the 3rd party {fmt} library (https://fmt.dev/latest/index.html) can be used instead of the <format> C++20 stdlib library.

I recommend getting Visual Studio 2022, though it requires Windows x64 to work. VS 2019 if you have a 32-bit CPU. The Community edition is free for non-commercial use.
https://visualstudio.microsoft.com/vs/community/

If you do get VS the default install setup doesn't include the "Desktop Development with C++" workload, you need to select that manually. If'n VS is already installed you can relaunch the installer and modify the install to add the workload. :)
Thanks George for the extra info on compilers and the IDE. I think most of the code should be easy to modify to make it compile on g++ (or whatever is running on my Fedora 36).
I will disregard my adversity to Microsoft and try out VS just to know what its about. I have already paid for CLion license.

thank you,
Well, you never mentioned your OS/compiler/IDE before now that I can see.... :D

Since C++20 is not doable with your current setup you probably should use https://www.learncpp.com/ as your source for learning C++ without spending more money. Better suited to the tools you have.

Gee, why no one ever mentioned Learn C++ before now I don't know. :Þ
ok George,
Just to make sure I am understanding the information in both of these sites:
https://gcc.gnu.org/projects/cxx-status.html
https://en.cppreference.com/w/cpp/compiler_support
Both of the them suggest that gcc supports basically all the features in C++ 20.
My lovely Fedora comes with gcc v. 12.
I guess I should not have problems working with C++ 20 as long as I set the right?
All I need to do is set the right standard when compiling right?
What exactly do you mean by "capable of properly using C++20" ?

thanks for the info again.
GCC 12 is not 100% fully C++20 compliant, there are core and library features that are only partially supported or not yet supported.

GCC is the closest to full compliance, behind Visual Studio. Modules and text formatting with <format> are two features I use and they are missing from GCC.

But you should set your language standard to C++20 or C++latest anyway. Unless you explicitly use a feature that is not in the later standards.

Modules is not a make-it-or-break-it feature IMO -- they are nice to have working -- you can still use #includes.

The 3rd party library {fmt} is a nice substitute for <format>. IIRC the C++ standard committee used {fmt} as their template for <format>.

https://github.com/fmtlib/fmt

Regarding modules vs. headers, there is an online only appendix PDF that accompanies the source examples for the Beginning C++20 book mention earlier. Goes into quite a lot of detail about non-module files.

https://github.com/Apress/beginning-cpp20

I gladly purchased the book, is worth the expense, and afterwards found the online PDF. Even more value for muh money! :)
Do take careful notice about GCC C++20 support as mentioned on the GCC GNU page you linked:

Important: Because the ISO C++20 standard is very recent, GCC's support is experimental.

In Plain Language, don't expect every C++20 feature to actually work with GCC. At. This. Time. Period.

Hopefully soon GCC will make the compiler 100% fully compliant.

I also really recommend you do NOT use GNU extensions, they potentially can create source code that can't be processed by non-GNU compilers.

Theoretically the C++20 (or earlier) source code I cruft can work with any C++20 compliant compiler, if it has the support. It is not Windows-specific in any manner.

Even Visual Studio can get cranky and whingey at times with C++20 features. Especially modules. *OY!*

It happens.....
Last edited on
Topic archived. No new replies allowed.