1. sizeof() 和strlen()
sizeof() and strlen()
1 #include <stdio.h>
2 #include <string.h>
3
4 void main()
5 {
6 char a[] = "good";
7 char mystr[100]="test string";
8
9 printf("sizeof a[]: %d \n", sizeof(a));
10 printf("strlen of a[]: %d \n", strlen(a));
11 printf("sizeof \"good\": %d \n", sizeof("good"));
12 printf("size of 'a': %d \n", sizeof 'a'); //字元常量的類型是int,根據提升規則,它由char轉換為int。結果和機器的字長相等
13 printf("sizeof mystr[]: %d \n", sizeof mystr);
14 printf("strlen of mystr[]: %d \n", strlen(mystr)); //在strlen()中,末尾的Null 字元不算數
15 }
輸出:
注意在C中,字元'a'的類型四int,而在C++中字元的類型為char。
2. C語言中符號的重載
static:
在函數內部,表示該變數的值在各個調用間一直保持延續性。
在函數這一級,表示該函數只對本文可見。
extern:
用於函數定義,表示全域可見(屬於冗餘的)。
用於變數,表示它在其他地方定義。
3. 什麼是定義,什麼是聲明?
定義:只能出現在一個地方,用於建立新的對象。它首先確定對象的類型,然後分配記憶體。例如:int my_array[100]
聲明:可以出現多次,用於指代其他地方(如其他檔案)定義的對象,它描述對象的類型。例如:extern int my_array[];
其實,只要記住下面的內容,就可以區分二者:
聲明相當於普通的聲明:它所說的並非自身,而是描述其他地方建立的對象。ertern對象聲明告訴編譯器對象的類型和名字,對象的記憶體配置則在別處進行。由於並未在聲明中為數組分配記憶體,所以並不需要提供關於數組長度的資訊。對於多位元組,需要提供最左邊一維數組之外的其他維的長度(給編譯器足夠的資訊產生代碼)。
定義相當於特殊的聲明:它為對象分配記憶體。
4. memcpy()和strcpy()
char * strcpy ( char * destination, const char * source );
Copy string
Copies the C string pointed by source into the array pointed by destination, including the terminating null character.
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
void * memcpy ( void * destination, const void * source, size_t num );
Copy block of memory
Copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination.
The underlying type of the objects pointed by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.
The function does not check for any terminating null character in source - it always copies exactly num bytes.
To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).