If I is an int variables and p and q are pointers to int whi

If I is an int variables and p and q are pointers to int, which of the following assignments are legal? p = i *p = &i; &p; = q p = &q; p = *&q; p = q p = *q *p = q *p = *q

Solution

A pointer contains address of a variable. To create a pointer of integer type the valid syntax is int *p. Now depending on the operating system the memory for pointer variable is allocated which could be 4 bytes or 8 bytes. If the pointer is of integer type then it should contain integer address. Following are the correct explainations.

a) p = i; here you are storing the value of i into p, p is a pointer of integer type and should store the address of integer variable therefore you need to typecast. You will get a warning during the execution.(still legal)

b) *p = &i; This is the correct syntax for storing the address of variable i into pointer p. (legal)

c) &p = q; This is invalid statement because & is used to know the address of a variable and since you cannot store the value of q into the address part of p hence this statement is invalid, you will get an error. (illegal).

d) p = &q; Here you are storing the address of a pointer into an interger pointer type. It will not throw an error just a warning but still its not valid. (illegal)

e) p = *&q; This is just another way of saying put p equals to whatever is inside of q. Since q is an integer type pointer and must contain the address of an integer type variable, therefore this statement is valid. (legal)

f) p = q; Same as option (e), hence valid. (legal)

g) p = *q; q is an integer pointer and contains the address of an integer pointer, *q means what value is present inside that address. Therefore it is similar to option (a). You will get a warning. (legal)

h) *p = q; Here you are trying to assign the address of an integer variable into an another integer variable to which p is pointing. Address of an integer variable can be of 4 bytes or 8 bytes of size but size of an integer variable is of 2 bytes. Therefore there is a loss of data, hence this statement is not valid although you will just get a warning. (illegal)

i) *p = *q; This is just assigning the value of a variable into another variable. (legal)

 If I is an int variables and p and q are pointers to int, which of the following assignments are legal? p = i *p = &i; &p; = q p = &q; p = *&q;

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site