1/04/2012

NCC Tutorial: Pointers 2

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:
int *p_int, ai=10, bi=12, ci=14;
char *p_char, ac='A', bc='L', cc='Z';
Now, using only the predefined pointers (p_int, p_char) on the left side of the assignments, we need to:
  1. Change values: ai=16, ac='N'
  2. Perform operations: bi=bi<<3 (multiplication by 2^3=8), bc=bc-'A'+'a' (conversion to lowercase)
  3. Use modified results: ci=ai+bi-ci, cc=bc
In every assignment, we need to keep on mind what address (i.e. what variable) is pointed to by our pointers. This excercise is based on that.

The solution, as simple as I can imagine it right now, is here:
// the first task
p_int = &ai;
*p_int = 16;
p_char = &ac;
*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;
The following values are supossed to be correct after those operations are over:
ai16
bi96
ci98
ac'N'
bc'l'
cc'l'
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!

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!