LZN's Blog CodePlayer

Scratch Notes for Stanford CS107: Programming Paradigm Ch03

2020-07-16
LZN

L3: Converting Between Types of Different Sizes and Bit Representations Using Pointers

Notes

Forced Type Conversion
double d=3.1416;
char ch=*(char *)&d; // 1. &d get d ref --> 2. (char *) use char point to &d --> 3. * deref by `char`

Another dangerous test:

short s=45;
double d=*(double *) &s;

Note double need 8 bytes to store the value, while short only takes 2 bytes, so this operation is very dangerious.

Big Endian and Little Endian:

See this plot:

NoAVI0.jpg

If copy a short type 1 from Big Endian machine to Little Endian machine, it will give a 256. Not a problem in forced type conversion.

Struct
struct fraction{
    int num;
    int denum;
};

fraction pi;

pattern:

||||pi.denum
||||pi.num
^
|
pointer

See the quirky syntax:

(fraction*)(&pi.denum))->num=12;

It first point to the original pi.denum (4 byte) and then interpret it to a fraction struct! What will happen? The orginal pi.denum is interpreted to a <new_struct> of fraction! Thus, ->num=12 will change the original `pi.denum` value!

Similar examples:

((fraction*)&(pi.denum))->denum=33;

What you will see: aRpkJs.png

Array

Actually, we need to accept the concept that verything in C/C++ is pointer, look at array:

array<=>&array[0]
array+k<=>&array[k]
*array<=>array[0]
*(array+k)<=>array[k]

If do this:

int array[10];
array[10]=1;

Be aware, this will not cause a compiler error as the C compiler is an efficiency-wise compiler, it will not do the bounce check. array[10] will be interpreted by 10*sizeof(a[0]), which is 40. Thus, from &array[0] and count for 40 bytes, that 4-byte space will be set to 1. This operation even tolerates negative numbers. (This is just code, not good code!) The neighbouring address is highly possible to be other variables. See activation record.

The above code is equivalent to:

*(array+10)=1;

There could be many crazy examples (Actually there is an error, you can find it): aRpkJs.png

Struct Array

Now we see the struct: aRulz8.jpg

The corresponding bit patterns in memory: KCwj.jpg](https://s1.ax1x.com/2020/08/06/aRKCwj.jpg)

Try this:

pupils[2].name=strdup("Adam");

Here a linked table like thing will work: aRKa0H.jpg

And this:

pupils[3].name=pupils[0].suid+6;

You will see: aRMRxK.jpg

Another one:

strcpy(pupils[1].suid, "40415xx");

aRQWYn.jpg

Null character \0 or NUL

Try a scary on:

strcpy(pupils[3].name,"123456")

See the result: aRld74.jpg

Generic Swap Important
void swap (int *ap, int *bp)
{
    int temp = *ap;
    *ap = *bp;
    *bp = temp;
}
int x=7;
int y=117;
swap(&7, &y);

See the flow: aRJaFg.jpg

Qustions

Glossary

Asterisk 星号 Ampersand 连i字符 synonymous 同义的 arithmetic 算数的 verbatim 逐字的 backslash 反斜线 jurisdiction 管辖权
two to the ninth 2^9 gibberish 胡言乱语 contrived (deliberately created rather than arising naturally or spontaneously)
phantom 幻影

Updated 2020-08-06


Comments

Content