16.5 Write a program to find whether a machine is big endian or little endian
Big-Endian和Little-Endian的定义如下:
1) Little-Endian就是低位字节排放在内存的低地址端,高位字节排放在内存的高地址端。
2) Big-Endian就是高位字节排放在内存的低地址端,低位字节排放在内存的高地址端。
举一个例子,比如数字0x12 34 56 78在内存中的表示形式为:
1)大端模式:
低地址 -----------------> 高地址
0x12 | 0x34 | 0x56 | 0x78
2)小端模式:
低地址 ------------------> 高地址
0x78 | 0x56 | 0x34 | 0x12
可见,大端模式和字符串的存储模式类似。
摘自:http://blog.csdn.net/ce123_zhouwei/article/details/6971544
bool isLittle() { short int a = 0x0001; char *c = &a; return c[0] == 1; }
16.6 Write a function called my2DAlloc which allocates a two dimensional array Minimize the number of calls to malloc and make sure that the memory is accessible by the
notation arr[i][j]
以下是图解:
int ** myDAlloc(int rows, int columns) { int head = rows * sizeof(int *); int contex = rows * columns * sizeof(int); int **array = (int **)malloc(head+ contex); int *p = (int *)(array + rows);// not (array + head ) for(int i = 0; i< rows; ++i) { array[i] = p + i * columns ; } return array; }