473,387 Members | 1,771 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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....december
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<iostream>

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 #1
13 2205
On Apr 2, 12:39 pm, Michael DOUBEZ <michael.dou...@free.frwrote:
Using pointer arithmetic, you forgot to increment p; use:
for(unsigned int i=0; i < arr_size; ++i,++p)

You can also use arr instead or just deference it:
for(unsigned int i=0; i < arr_size; ++i)
std::cout << arr[i] << std::endl;
Michael

OOPS!, sorry

Apr 2 '07 #2
OK, i have a little of improvement. what do you say?

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

STSTAMENT:
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<iostream>

void print_arr(const char**);

int main()
{
const size_t MonthsInYear = 12;

const char* arr[MonthsInYear + 1] =
{"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november",
"december", '\0'};
print_arr(arr);

return 0;
}
void print_arr(const char** arr)
{
std::cout << "\n\tUSING FUNCTION\n";
for(const char** p = arr; *p != '\0' ; ++p)
std::cout << *p << std::endl;
}

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

USING FUNCTION
january
february
march
april
may
june
july
august
september
october
november
december
[arch@voodo tc++pl]$

Apr 2 '07 #3
On 2 Apr, 10:07, "arnuld" <geek.arn...@gmail.comwrote:
OK, i have a little of improvement. what do you say?

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

STSTAMENT:
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<iostream>

void print_arr(const char**);

int main()
{
const size_t MonthsInYear = 12;

const char* arr[MonthsInYear + 1] =
{"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november",
"december", '\0'};

print_arr(arr);

return 0;

}

void print_arr(const char** arr)
{
std::cout << "\n\tUSING FUNCTION\n";
for(const char** p = arr; *p != '\0' ; ++p)
std::cout << *p << std::endl;

}
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;

}

--
Erik Wikström

Apr 2 '07 #4
On Apr 2, 1:47 pm, "Erik Wikström" <eri...@student.chalmers.sewrote:

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. does it work like this:

*arr == &arr[0]
++arr == &arr[0 + 1]

?

IOW, like a pointer

Apr 2 '07 #5
On 2 Apr, 11:00, "arnuld" <geek.arn...@gmail.comwrote:
On Apr 2, 1:47 pm, "Erik Wikström" <eri...@student.chalmers.sewrote:
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. does it work like this:

*arr == &arr[0]
++arr == &arr[0 + 1]

?

IOW, like a pointer
Yes, arr[N] is the same as *(arr[0] + N) == *(arr + N).

The following might help you understand but should *never* be used in
real life, read the rest at your own risk:
Using the transitivity of addition (meaning that A+B == B+A) we can
get some pretty ugly, but valid, syntax when indexing into arrays:

So arr[N] == *(arr + N) then we apply the transitivity rule on the
left hand giving *(N + arr) and then go back to the array-form gives
N[arr].

So given array arr then 2[arr] will give the third element in arr. And
then we replace the N with a variable and we get something like this:

int main()
{
int arr[3] = {1, 2, 3};
for (int i = 0; i < 3; ++i)
std::cout << i[arr];
return 0;
}

--
Erik Wikström

Apr 2 '07 #6
* Erik Wikström:
>
Using the transitivity of addition (meaning that A+B == B+A)
ITYM commutativity.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Apr 2 '07 #7
On 2 Apr, 11:40, "Alf P. Steinbach" <a...@start.nowrote:
* Erik Wikström:
Using the transitivity of addition (meaning that A+B == B+A)

ITYM commutativity.
Ah, yes.

--
Erik Wikström

Apr 2 '07 #8
arnuld wrote:
OK, i have a little of improvement. what do you say?
const char* arr[MonthsInYear + 1] =
{"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november",
"december", '\0'};
void print_arr(const char** arr)
{
std::cout << "\n\tUSING FUNCTION\n";
for(const char** p = arr; *p != '\0' ; ++p)
std::cout << *p << std::endl;
}
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).

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


Brian
Apr 2 '07 #9
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 :-)

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
Brian

Apr 2 '07 #10
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...@gmail.comwrote:
On Apr 2, 1:47 pm, "Erik Wikström" <eri...@student.chalmers.sewrote:
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 objektorientierter Datenverarbeitung
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...@gmail.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 objektorientierter Datenverarbeitung
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...@gmail.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 objektorientierter Datenverarbeitung
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
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...
9
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...
16
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...
11
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...
6
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...
1
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...
14
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:...
5
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...
6
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...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...

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.