Thursday, January 28, 2010

OOP Challenge

The first official challenge of this semester
http://zenit.senecac.on.ca/wiki/index.php/OOP344#Challenge

Basic idea is to convert the integer into a string and then use bio_putstr(const char*) to display it.

Here is the solution:

138 void bio_putint(int val){
139 char temp[20] = "";
140 int i = 0;
141 int j = 0;
142 int length = 0;
143 int scale = 1;
144 if (val == 0)
145 bio_putch('0');
146 else{
147 for (i = 1, length = 0; val / i != 0 ; i *= 10, length++);
148 if (val > 0) {
149 for (i = 0; i < length; i++){
150 scale = 1;
151 for (j = 0; length - j > i + 1; j++)
152 scale *= 10;
153 temp[i] = (val / scale) % 10 + 48;
154 }
155 temp[i] = '\0';
156 }
157 else {
158 val *= -1;
159 temp[0] = '-';
160 for (i = 0; i < length; i++){
161 scale = 1;
162 for (j = 0; length - j > i + 1; j++)
163 scale *= 10;
164 temp[i+1] = (val / scale) % 10 + 48;
165 }
166 temp[i+1] = '\0';
167 }
168 }
169 bio_putstr(temp);
170 }


Tested on matrix. I strongly believe it can work on the other three platform. :-]

Monday, January 25, 2010

Pointer in C

We discussed pointer in C language in today's OOP344 class, and I understand some concepts which I get confused before.

Below is an example:
1 int a = 10;
2 int* p = &a;
3 printf("%u, %u, %d, %d\n", p, &a, *p, a);
4 p++;
5 printf("%u, %u, %d, %d\n", p, &a, *p, a);

The output of the second printf confuses me. I thought the last two number should be the same and unknown. In fact, that's not the case.
In line 4, only the value of p changed, the value of a remained the same. If I want the value of the last two number which are to be printed on line 5 to be the same, then I should code :
(*p)++; //++ has higher priority than *
Then both *p and a will be 11.

Another example
int a[5] = {1,2,3,4,5};
int* p = a;
The addresses of p and a are the same, rather than in different location but pointing to the same position.

In addtion, we can have a pointer pointer. It is like this:
int* p = &a;
int** q = &p;
In this way, we can manipulate the pointer pointing to other places inside a function.

Monday, January 11, 2010

Test

This is my first English Blog, I am just testing.