Peter
Peter

Reputation: 2320

the c++ programming language, chapter 5.9 exercise 1

From the book:

Write declarations for the following: a pointer to a character, an array of 10 integers, a ref-erence to an array of 10 integers, a pointer to an array of character strings, a pointer to a pointer to a character, a constant integer, a pointer to a constant integer, and a constant pointer to an integer. Initialize each one.

I'm confused by "a pointer to an array of character strings". What does Stroustrup want? Is this to be meant literally? In which way?

The straight and simple solution:

char* c[] = {"foo", "bar", "baz"};
char** c_ptr;

Or this one:

typedef char carray[20];
typedef array* carray_ptr;
carray_ptr ptr = new carray[10];

What do you think? (Okay, a pointer to pointer isn't very straight.)

Upvotes: 2

Views: 1087

Answers (4)

Kerrek SB
Kerrek SB

Reputation: 477100

Break it down into steps:

  1. A pointer to an array: T (*p)[N]

  2. T = char const * gives you: char const * (*p)[N]

  3. We initialize a pointer with the address of an existing thing, so make an array first:

    char const * arr[] = { "hello", "world" };

  4. Now initialize the guy from (2): char const * (*p)[2] = &arr;

Upvotes: 0

paulsm4
paulsm4

Reputation: 121669

1) Chapter 5 is about "Pointers, Arrays and Structures". I don't see any "typedef's" skimming the chapter, so I wouldn't use them in this exercise.

2) One could point to "argv" as an excellent example of "A pointer to an array of character strings":

int main (int argc, char *argv[])

3) "c_ptr" in your first example would certainly work (although maybe a better name might be "c_pp" ;)):

char* c[] = {"foo", "bar", "baz"};
char** c_ptr = c;

'Hope that helps!

Upvotes: 0

Mooing Duck
Mooing Duck

Reputation: 66922

typedef char* character_string;
typedef character_string[20] array_of_character_strings;
typedef array_of_character_strings* pointer_to_array_of_character_strings;
pointer_to_array_of_character_strings ptr; //done

or:

char*(*var)[20];

shown at: cdecl.ridiculousfish.com, "declare var as pointer to array 20 of pointer to char"

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224964

With these sorts of declaration tests, it's often easiest to use a tool like cdecl. I think in this case what the book is looking for is:

c

is a pointer:

*c

to an array:

(*c)[]

of character strings:

char *(*c)[]

Or from cdecl:

cdecl> declare c as pointer to array of pointer to char
char *(*c)[]

I just made a guess about what the book expects, but since the next request is "pointer to a pointer to a character", it would be weird for the two to be asking the same thing.

Upvotes: 2

Related Questions