this is an assignment homework

I have defined a structure X....

struct X{
string name;
char grade;
};

here are the questions
a) Declare r as a variable of X, s as a pointer variable to X and w as a pointer variable to a pointer of X.

X r, *s, **w;

...just hope anyone would help on this
my answers to other parts would depend on the above answer...

b)assign a newly created dynamic array of 99999 pointers of X to w.

w=new &&X[99999];

c)assign the address of r to the last entry of w.

w[99998]=&r;

d)assign " Chan Tai Man" to the name of the structure pointed by w[5]

w[5]->name="Chan Tai Man"

e)swap the values of the first two entries of w, using s as a temporary store.

s = w[0];
w[0]=w[1];
w[1]=s;

f) release the dynamic array to the freestore of the OS

delete []w;

Recommended Answers

All 3 Replies

b)assign a newly created dynamic array of 99999 pointers of X to w.

w=new &&X[99999];

Erm, close. Let's start with s first:

s = new X[99999];

The difference between s and w is one level of indirection, so the new[] expression should reflect that in the type:

w = new X*[99999];

It helps if you think of it like new <type>[[/B][I]<count>[/I][B]], where <type> matches the declaration of your pointer with one level if indirection removed. w is defined as X** , so stripping off one level of indirection produces X* .

d)assign " Chan Tai Man" to the name of the structure pointed by w[5]

w[5]->name="Chan Tai Man"

Careful, at this point w[5] is an uninitialized pointer. You can't safely dereference it. But the syntax is correct (barring a missing semicolon at the end).

so what should be the code for part (d)??

should it be

**w[5]->name="Chan Tai Man";

just to check if my concept is correct. are the following statements all correct?

X a,*b,**c;
b = &a;
c = &b;
c = &&a;
b = new X;
b = new X[2];

so what should be the code for part (d)??

The code is already correct, assuming at some point prior to that line you've pointed w[5] to an object of type X.

>c = &&a;
This is not correct. && is not a valid operator for this case (it's not a valid operator at all except in the current unreleased standard). It's not a valid combination of & operators either, because & requires the operand to be an lvalue and &a is an rvalue.

In any case, you can't say &&obj or &&&obj, or any number of multiple address-of operators to make a pointer to a pointer to [...] an object. Have you even tried to compile these lines?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.