版權聲明:本文爲博主原創文章,未經博主允許不得轉載。
發現好多人搞不清楚數組和指針的區別。
數組申明時編譯器自動分配一片連續的內存空間
指針申明時只分配了用於容納指針的4字節空間
作爲函數參數時,數組參數和指針參數等價
數組名在多數情況下可視爲常量指針,其值不能改變
指針的本質是變量,保存的值被看做內存中的地址。
名字上的區別:
- int a[5];
- a和&的意義不同,a是數組元素的首地址,&a是整個數組的地址
- #include <stdio.h>
- int main()
- {
- int a[5] = {1,2,3,4,5};
- int *p1 = (int *)(&a + 1);
- int *p2 = (int *)(a + 1);
- printf("p1[-1] = %d\n",p1[-1]);<span style="white-space:pre"> </span>//5
- printf("p2[-1] = %d\n",p2[-1]);<span style="white-space:pre"> </span>//1
- }
複製上的區別:
- <span style="white-space:pre"> </span>int a1[5] = {1,2,3,4,5};
- int a2[5];
- a2 = a1; //oOps
- for(int i = 0;i < 5;i++)
- {
- a2[i] = a1[i]; //*a2++ == *a1++
- }
- char *p1 = "hello";
- char *p2 = NULL;
- p2 = p1; //正確,p2也指向了hello所在內存空間
計算內存空間大小的區別:
- <span style="white-space:pre"> </span>char s1[] = {'a','\0','c','c'};
- int s2[] = {0,1,2,3,4,5,6,7,8};
- printf("%d\n",strlen(s1));
- printf("%d\n",strlen(s2));
- size_t strlen(const char *str)
- {
- int len = 0;
- assert(str != NULL);
- while(*str != '\0')
- {
- len++;
- }
- return len;
- }
看了原型大家都知道上面的結果是怎麼來的了。再次強調求數組所佔內存空間用sizeof關鍵字。
字符串數組和字符數組:
- char s1[] = {'h','e','l','l','o'};
- char s2[] = "hello";
- printf("%d\n",sizeof(s1));
- printf("%d\n",sizeof(s2));<span style="white-space:pre"> </span>//printf("%d\n",strlen(s2));結果是6
結果分別是4和5,在C中並沒有字符串數據類型,只是用字符數組進行模擬,在最後以‘\0’結束;
字符串數組和字符串:
- char s1[] = "hello";
- char *s2 = "hello";
- s1[1] = 'H';
- s2[1] = 'H'; //oOps
這裏主要是有個存儲位置的問題。s2指向的一個字符串字面量,存在在只讀代碼段,其值不能被修改,s1是字符串數組存在棧空間。
作爲形參傳遞:
- void fun(int a[5]) <==> void fun(int a[]) <==> void fun(int *a)
所以在傳遞數組的時候還需要另一個參數,指示數組大小。其他情況
- void fun(int *a[5]) <==> void fun(int *a[]) <==> void fun(int **a)
- void fun(int a[5][6]) <==> void fun(int a[][6]) <==> void fun(int (*a)[6])
定義數組使用爲指針,定義爲指針,使用爲數組:
- //b.c
- #include <stdio.h>
- char str[] = "hello";
- //a.c
- #include <stdio.h>
- extern char *str;
- int main()
- {
- printf("%s",str); //oOps,正解printf("%s",(char *)&str);
- return 0;
- }
- //b.c
- #include <stdio.h>
- char *str = "hello";
- //a.c
- #include <stdio.h>
- extern char str[];
- int main()
- {
- printf("%s",str);//輸出什麼?正解:printf("%s",(char *)(*(unsigned int *)str));
- return 0;
- }
引用:http://blog.csdn.net/z1179675084/article/details/12951323