想要把丟掉的東西撿起來,還是很辛苦啊,今天我就發現,我連char* 和 char []的區別都不知道。
很多人覺得這兩個定義效果一樣,其實差別很大。以下是個人的一些看法,有不正確的地方望指正。
本質上來說,char *s定義了一個char型的指針,它只知道所指向的內存單元,並不知道這個內存單元有多大,所以:
當char *s = "hello";后,不能使用s[0]='a';語句進行賦值。這是將提示內存不能為"written"。
當用char s[]="hello";后,完全可以使用s[0]='a';進行賦值,這是常規的數組操作。
若char s[] = "hello";
char *p = s;
也可以使用p[0] = 'a';因為這是p ==s,都是指向數組的指針。
下面看另外一種定義:
char *s = (char *)malloc(n(www.111cn.net));//其中n為要開辟空間的大小
這句話其實相當於:
char s[n];定義的也是一個指向數組的指針,便可進行數組的下標操作
例子
代碼如下 復制代碼
#include <stdio.h>
int main(int argc, char* argv[]) {
char* buf1 = "this is a test";
char buf2[] = "this is a test";
printf("size of buf1: %d\n", sizeof(buf1));
printf("size of buf2: %d\n", sizeof(buf2));
return 0;
}
結果是:
$ > ./main
size of buf1: 4
size of buf2: 15
from:http://www.111cn.net/net/c/66247.htm
相關內容
- 2014.02.15解決ASP.NET MVC3與FusionCharts亂碼問題
- 2011.01.03asp.net看charipet常用字段與靜態方法
- 2011.01.01nchar,char,varchar與nvarchar區別
- 2010.12.26Java 和 C/C++ 中的char 類型長度學習筆記
- 2010.12.25String,PChar,PByte,Array of Char,Array of Byte
- 2009.10.11CString, int, string, char*之間的轉換
- 2008.04.26char,TCHAR,WCHAR區別
- 2008.01.12ComponentOne之WebChart用法
