473,795 Members | 2,443 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Stroustrup 5.9, exercise 10 (using a function)

this does not work, i know there is some problem in the "for loop" of
"print_arr" function. i am not able to correct the weired results i am
getting. i have no compile time error, it is only semantic-bug that is
causing the trouble:

EXPECTED: january, february, march....decemb er
GOT: january, january, january........ .january

------------- PROGRAMME --------------
/* Stroustrup, 5.9, exercise 10

STATEMENT:
define an array of strings,where strings contains the names months .
Print those strings. Pass the array to a function that prints those
strings.

SOLUTION:

1.) 1st, i will print array int he "main" using "for" loop and array
indexing.

2.) then i wil print he array using a function and passing the array
to the function as argument(pass by reference).

NOTICE: posted code is implementation of (2)
*/

#include<iostre am>

void print_arr(const char**, size_t);

int main()
{
const char* arr[] = {"january", "february", "march", "april", "may",
"june",
"july", "august", "september" , "october",
"november",
"december"} ;

const size_t arr_size = sizeof(arr) / sizeof(*arr);

print_arr(arr, arr_size);

return 0;

}

void print_arr(const char** arr, size_t arr_size)
{
const char** p = arr;

std::cout << "\n\tUSING FUNCTION\n";
for(unsigned int i=0; i < arr_size; ++i)
std::cout << *p << std::endl;

}

-------------- OUTPUT ----------------------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra 5.9_ex-10-
function.cpp
[arch@voodo tc++pl]$ ./a.out

USING FUNCTION
january
january
january
january
january
january
january
january
january
january
january
january
[arch@voodo tc++pl]$

Apr 2 '07
13 2238
arnuld wrote:
On Apr 2, 9:55 pm, "Default User" <defaultuse...@ yahoo.comwrote:

I don't like the use of '\0' there. While it's technically not
wrong, as that's a legitimate null pointer constant, I think it
betrays a lack of understanding on your part.

:-(
That last element of the array is NOT a character, particularly it
is not a character like the null terminator in a character array
(C-style string).

well, its a new thing you told :-)
That's fine. You're in a learning situation, so details can be
important.
>
What you want in this case for an array terminator is a null
pointer. I'd prefer the use of a plain 0, or even NULL (although
many in the C++ community don't care for that macro).

OK, 0 (zero) then
That would be better. Whether it's better than maintaining and passing
the size is a design question.


Brian
Apr 2 '07 #11
On Apr 2, 11:00 am, "arnuld" <geek.arn...@gm ail.comwrote:
On Apr 2, 1:47 pm, "Erik Wikström" <eri...@student .chalmers.sewro te:
Personally I'd prefer a version where the size is passed as an
argument just to be safe, something like your first try, but also
incrementing arr:
void print_arr(const char** arr, size_t arr_size)
{
std::cout << "\n\tUSING FUNCTION\n";
for(unsigned int i=0; i < arr_size; ++i, arr++)
std::cout << *arr << std::endl;
}
this is the 1st time i have seen someone incrementing an "array",
never saw so even in any book.
There's no array in this function, just a pointer.
does it work like this:
*arr == &arr[0]
++arr == &arr[0 + 1]
?
IOW, like a pointer
If you look at the declaration of the function, it's a pointer.

Had he wanted to confuse you, he could have declared the
function:

void print_arr( char const* arr[], size_t size ) ...

Despite appearances, there's no array here either. There's a
special rule that says when the type of a function parameter is
declared to be array of T, the actual type is pointer to T.

And pointers can be incremented.

Never the less, I'd keep it simple:

void print_arr( char const* arr[], size_t size )
{
for ( size_t i = 0 ; i < size ; ++ i ) {
std::cout << arr[ i ] << std::endl ;
}
}

or (more idiomatic, because closer to what you do with the STL,
but perhaps less readable anyway):

void print_arr( char const** arr, size_t size )
{
char const** end = arr + size ;
while ( arr != end ) {
std::cout << *arr << std::endl ;
++ arr ;
}
}

Note, however, the ambiguity in the use between pointers and
arrays. The definition of the [] operator is a[b] == *(a+b).
Always. You can index arrays because an array converts
implicitly to a pointer to the first element in most contexts.
And the [] is defined as a pointer operator, not an array
operator. Note that this means that things like "abcd"[ i ],
or even i[ "abcd" ] are legal (where i is an int)---if a[b] is
legal, so is b[a]. (Obviously, putting the index in front of
the braces is only good for obfuscation. But realizing that it
is legal, and why, does help understanding the oddities of
arrays in C and in C++. And why so many people prefer
std::vector to a C style array:-).)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 3 '07 #12
On Apr 2, 11:29 am, "Erik Wikström" <eri...@student .chalmers.se>
wrote:
On 2 Apr, 11:00, "arnuld" <geek.arn...@gm ail.comwrote:
Yes, arr[N] is the same as *(arr[0] + N) == *(arr + N).
You mean *(&arr[0] + N), I'm sure.

I'd point out, at least, that there are in fact two curiousities
involved there. One, of course, is the fact that the indexing
operator is defined in terms of pointer arithmetic. The second
is the fact that an expression with array type converts
implicitly, and in (far too) many contexts to a pointer to the
first element.

The whole thing has been carefully designed to confuse beginners
in the language, and thus keep the rates for freelance
specialists higher. Personally, as a freelance specialist, I'm
all for it.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 3 '07 #13
On Apr 2, 8:30 pm, "arnuld" <geek.arn...@gm ail.comwrote:
On Apr 2, 9:55 pm, "Default User" <defaultuse...@ yahoo.comwrote:
I don't like the use of '\0' there. While it's technically not wrong,
as that's a legitimate null pointer constant, I think it betrays a lack
of understanding on your part.
That last element of the array is NOT a character, particularly it is
not a character like the null terminator in a character array (C-style
string).
well, its a new thing you told :-)
Then maybe we should back up a bit. An array is (by definition,
I think, and independantly of the language) a sequence of
elements, all having the same type. In your case, that type was
char const*, a *pointer* (to char). If the array contains
pointers, it cannot, ever, contain a character. The only reason
the compiler didn't complain when you put '\0' into the array is
because there are a lot (far too many, in fact) of implicit
conversions, which C++ inherits from C.
What you want in this case for an array terminator is a null pointer.
I'd prefer the use of a plain 0, or even NULL (although many in the C++
community don't care for that macro).
OK, 0 (zero) then
Which also invokes an implicit conversion. As does NULL: the
argument for NULL is that is says what you want (i.e. a special
value for a pointer). The argument against NULL that it doesn't
actually give you what it says. (G++ warns if you misuse it,
i.e. if you use it in a context where it doesn't get immediately
converted into a pointer. Which pretty much negates the main
argument against it.)

The problem is serious enough that there is a proposal to add a
"nullptr" to C++, which has been adopted by the committee for
C++09.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 3 '07 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
3156
by: Oplec | last post by:
Hi, I am learning standard C++ as a hobby. The C++ Programming Language : Special Edition has been the principal source for my information. I read the entirety of the book and concluded that I had done myself a disservice by having not attempted and completed the exercises. I intend to rectify that. My current routine is to read a chapter and then attempt every exercise problem, and I find that this process is leading to a greater...
9
2268
by: arnuld | last post by:
problem: define a /struct Date/ to keep track of dates. provide functions that read Dates from input, write Dates to output & initialize a date with date. solution: i thought of a /vector/ of /Date structures/. "Date" struct carries 3 things: month, date & year. i wrote the following code & of course it gives an error: #include <iostream>
16
2375
by: arnuld | last post by:
i did what i could do at Best to solve this exercise and this i what i have come up with: ----------- PROGRAMME -------------- /* Stroustrup 5.9, exercise 3 STATEMENT: Use typedef to define the types: unsigned char
11
1844
by: arnuld | last post by:
/* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice: 1.) using ar array of char for names of months and an array of numbers for number of days. 2.) using an array of structures. each structure holds the name of the
6
3044
by: arnuld | last post by:
this one was much easier and works fine. as usual, i put code here for any further comments/views/advice: --------- PROGRAMME ------------ /* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice:
1
322
by: arnuld | last post by:
this does not work, i know there is some problem in the "for loop" of "print_arr" function. i am not able to correct the weired results i am getting. i have no compile time error, it is only semantic-bug that is causing the trouble: EXPECTED: january, february, march....december GOT: january, january, january.........january ------------- PROGRAMME -------------- /* Stroustrup, 5.9, exercise 10
14
2481
by: arnuld | last post by:
there is no "compile-time error". after i enter input and hit ENTER i get a run-time error. here is the code: ---------- PROGRAMME -------------- /* Stroustrup, 5.9, exercise 11 STATEMENT: Read a sequence of words from the input. use "quit" as the word
5
468
by: arnuld | last post by:
i am not able to come up with any solution for this. i am not even able to think of one line of code for this solution. /* Strouostrup, 5.9, exercise 12 * * * STATEMENT: * write a function that counts the number of occurrences of a pair of * letters ina "string" and another that does the same in a zero- terminated
6
2480
by: arnuld | last post by:
This one works to seem fine. Can I make this program better ? 1) the use of get(ch) function was inspired from Stroustrup 21.5.1, page number 638. 2) I see, when you create an object of std::ifstream while passing a pointer to it, it automatically opens the file. 3) If I open a file using std::ostream, then I am confused whether it will open the file for writing or appending ?.
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10438
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10214
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7540
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.