char str[] = "ABCDE"; // sizeof(str): 6
char *p = str; // sizeof(p): 4
char q = *str; // sizeof(q): 1
int n = 10; // sizeof(n): 4
int *ptr = &n; // sizeof(ptr): 4 ; sizeof(*ptr): 4
|
char的pointer之size是4 (因為存的是位置)
char本身是1 (存的是資料)
========================================================================
int arr[] = {6, 7, 8, 9, 10};
int *ptr = arr;
*ptr++ += 123;
*++ptr += 123;
int *p = arr;
int *q = arr + sizeof(arr)/sizeof(*arr);
while( p != q )
cout << *p++ << " "; //129 7 131 9 10
|
*ptr++
等價於
*(ptr++)
compound assignment operator:
將 right-hand operand 加到左邊, 再將結果存入 left-hand operand
(assignment是最後做!)
(assignment是最後做!)
*ptr++ += 123;
左邊取值6 (位置仍在6), 將123 + 6 = 129 assign到 6 的位置, 完成後 ptr 前進到 7 的位置
*++ptr += 123;
左邊先前進到8的位置, 取值8, 將123 + 8 = 131 assign到 8 的位置
注意這兩個意義不一樣:
*ptr++ += 123;
*ptr++ = *ptr++ + 123;
========================================================================
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
printf("size of arr1 = %d\n", sizeof(arr1)); // 32
printf("size of arr2 = %d\n", sizeof(arr2)); // 4
printf("size of arr3 = %d\n", sizeof(arr3)); // 32
|
========================================================================
union{
int num;
unsigned char n[4];
}q;
q.num = 10;
for( int i = 0 ; i< 4 ; i++)
printf("%x ", q.n[i]); // a 0 0 0
|
此片段可用來判斷機器是little-endian
10 => 0 0 0 a
n ->a
n+1 ->0
n+2 ->0
n+3 ->0
(由尾端開始放入memory, 記得前題都是記憶體位置 低到高/小到大/index 0到n)
========================================================================
#include <iostream>
using namespace std;
class Animal{
public:
Animal() { cout << "Animal" << endl; }
~Animal() { cout << "~Animal" << endl; }
void move() { cout << "Animal move" << endl; }
virtual void eat() { cout << "Animal eat" << endl; }
};
class Dog: public Animal{
public:
Dog() { cout << "Dog" << endl; }
~Dog() { cout << "~Dog" << endl; }
void move() { cout << "Dog move" << endl; }
void eat() { cout << "Dog eat" << endl; }
};
int main( ){
{
Dog dog; // Animal
// Dog
Animal *pAnimal = &dog;
Dog *pDog = &dog;
pAnimal->eat(); // Dog eat
pAnimal->move(); // Animal move
pDog->eat(); // Dog eat
pDog->move(); // Dog move
} // ~Dog
// ~Animal
{
Dog *pDog = new Dog(); // Animal
// Dog
Animal *pAnimal = pDog;
pAnimal->eat(); // Dog eat
pAnimal->move(); // Animal move
pDog->eat(); // Dog eat
pDog->move(); // Dog move
delete pAnimal; // ~Animal
}
}
|
========================================================================
cout << sizeof(short int) << endl; // 2
cout << sizeof(unsigned short int) << endl; // 2
cout << sizeof(unsigned int) << endl; // 4
cout << sizeof(int) << endl; // 4
cout << sizeof(long int) << endl; // 4
cout << sizeof(signed char) << endl; // 1
cout << sizeof(unsigned char) << endl; // 1
cout << sizeof(float) << endl; // 4
cout << sizeof(double) << endl; // 8
cout << sizeof(long double) << endl; // 12
|
short int = short
long int = long
好像是Mstar的考題?
回覆刪除