In NCC Tutorial: Pointers 1, I introduced * and & operators to you. In this one, I'll try to explain them through an example, so you get to know them better.
The task in the example is to assign different values and perform some operations on some predefined variables using only pointers in the assignments. We are going to use an int and a char pointer, and 6 different variables, three of each kind. So, say in the beginning we are given this peice of code:
The solution, as simple as I can imagine it right now, is here:
If you had something like this on your mind, you were right. After reading this, you are supposed to understand the pointers, referencing and dereferencing basics. NCC Tutorial: Pointers 3 will be about connections between pointers and arrays. Keep practicing, ask whatever you want and good luck with coding!
The task in the example is to assign different values and perform some operations on some predefined variables using only pointers in the assignments. We are going to use an int and a char pointer, and 6 different variables, three of each kind. So, say in the beginning we are given this peice of code:
Now, using only the predefined pointers (p_int, p_char) on the left side of the assignments, we need to:int *p_int, ai=10, bi=12, ci=14; char *p_char, ac='A', bc='L', cc='Z';
- Change values: ai=16, ac='N'
- Perform operations: bi=bi<<3 (multiplication by 2^3=8), bc=bc-'A'+'a' (conversion to lowercase)
- Use modified results: ci=ai+bi-ci, cc=bc
The solution, as simple as I can imagine it right now, is here:
The following values are supossed to be correct after those operations are over:// the first task p_int = &ai; *p_int = 16; p_char = ∾ *p_char = 'N'; // the second task p_int = &bi; *p_int << 3; p_char = &bc; *p_char -= 'A'+'a'; // the third task p_int = &ci; *p_int = ai+bi-ci; p_char = &cc; *p_char = bc;
ai | 16 |
bi | 96 |
ci | 98 |
ac | 'N' |
bc | 'l' |
cc | 'l' |
No comments:
Post a Comment
If you have anything useful to say (ideas, suggestions, questions, business proposals, or just "Thank you!"), please feel free to comment! Also, you can use my e-mail and/or find me on Twitter!