C Tips:需要注意的地方

結構體聲明:

struct classA {...};      // struct classA x1;
typedef struct {...} classB; // classB x2;
typedef struct classA {...} classC; // classC x3;   <==> struct classA x3;
classA的定義必須加struct結構標籤;用typedef進行類型定以後,classB可直接用於定義;classC的定義兩種方法均可使用。

文件讀寫結構體:

fwrite(&somestruct, sizeof somestruct, 1, fp);
fread(&somestruct, sizeof somestruct, 1, fp);

不需要臨時變量,交換a,b值

// 根據方法 1,同理可推出其他方式
a = a + b;
b = a - b;
a = a - b;

後綴++和--操作符比前綴一元操作符高

*p ++; // 等價於 *(p++)

C語言中沒有通用的指針類型

// 用void **通用指針作爲參數,但不可移植
void func(void **); 
double *dp;
func((void **)&dp); 

char a[] 和 char *p不等價

char a[] = "hello";  // a 即爲"hello"字符串 , a[i] = 'p' 可以更改
char *p = "world";   // p 存取"world"的地址 , p[i] = 'p' 不可更改 , 屬於無名的靜態數組

調用free()後,指針指向的內存被釋放,但指針並沒有置空,最後在釋放之後立即將它們置爲NULL,以明確狀態。

sizeof()不能告知指針所指內存的大小,只能得到指針本身的大小。實際上,沒有什麼可移植的方法得到malloc()函數分配的內存塊大小。

calloc()和malloc()的區別:

p = calloc(m, n); 

<==>

p = malloc( m * n );
memset(p, 0, m * n);

C語言中字符常量是int類型,與C++不同,C++中爲char類型

int conLen = sizeof('a') ;   // 4
int intLen = sizeof(int);    // 4
int charLen = sizeof(char);  // 1

// 前兩個可以互換,表示*p的值爲可讀
// 第三個指的是指針p不可修改,屬於指針常量
const char *p;
char const *p;
char * const p;

把stdin或stdout重定向到文件,stdout/stdin爲常量,因此不能進行賦值;一旦使用freopen後,無法恢復到原來的stdout/stdin,因此最好一開始就不要用

FILE *saveStdout = stdout;
freopen(fileName, "w", stdout);
stdout = fopen(fileName, "w"); // wrong
stdout = saveStdout; // wrong



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章