Question:
C++ please help urgent!?
?
2012-04-14 18:37:53 UTC
Given the following code, select the best answer that describes what the code does.

int n;
int *a;
int *b;
a = &n;
b = a;

a. The value of n is copied to b.
b. The memory address stored in a is copied into b.
c. The memory address stored in b is copied into a.
d. The pointer a is now pointing to a different object. (I think it's this one)

Given the following declarations, indicate whether each subsequent statement is valid or invalid.
int x;
int *ptr;

a. int *ptr2 = x; (invalid?)
b. &ptr = x; (invalid?)
c. int *ptr2 = ptr; (valid?)
d. int *ptr2 = *ptr; (invalid?)
Three answers:
t
2012-04-14 18:59:17 UTC
Q1

What this code does:

- declare an int variable called 'n'

- declare an int pointer called 'a'

- declare an int pointer called 'b'

- take the address of 'n' and store it in 'a'

- take the memory address stored in 'a' and put a copy of it in 'b'

The correct answer is "b. The memory address stored in a is copied into b"



Q2

Yes, you are correct.

a. Invalid: pointer must contain an address but x contains an int, not an address

b. Invalid: the address of a variable is an R-value (read only, cannot be assigned to)

c. Valid: 'ptr' contains a memory address and it's valid to store a copy of it in 'ptr2'

d. Invalid: 'ptr2' must contain an address, but dereferencing 'ptr' gives an int
roger
2012-04-15 20:20:54 UTC
int n;

int *a;

int *b;

a = &n;

b = a;



a. The value of n is copied to b. NO the address of n is copied into b (not its value)

b. The memory address stored in a is copied into b. Yes

c. The memory address stored in b is copied into a. no

d. The pointer a is now pointing to a different object. (I think it's this one) Nope a is a variable that can hold an address -- it holds a random address before the assignment. You could think of it as pointing to a random object and now it points to a different object i.e. n



Given the following declarations, indicate whether each subsequent statement is valid or invalid.

int x;

int *ptr;



a. int *ptr2 = x; (invalid?) ptr2 not declared (invalid)

if you meant

int *ptr =x ; then you are making a pointer froman interger without a cast (and x is not initialized so it has a random value)

b. &ptr = x; (invalid?) invalid can't change the address of ptr

c. int *ptr2 = ptr; (valid?) if ptr2 is declared as int *ptr2 then it is valid if ptr has been assigned a valued. int *ptr2 = *ptr; (invalid?) invalid assigning an integer to a pointer without a cast

* ptr is an integer (the one that ptr points to)
Mr. Anderson
2012-04-15 01:43:10 UTC
My gosh is this really what people taking computer science classes have to go through? =/


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...