標籤:c語言 變數 儲存 記憶體
1、變數類型:
C語言的變數分為局部變數和全域變數。
1.局部變數:
指在函數內部或者塊內部(即一對花括弧包含的地區)[以下均稱為塊]定義的變數,只對區塊範圍內有效。
特點:不同塊中可以有同名變數名,代表不同的變數,互不干擾;函數形參也是局部變數。
2.全域變數:
在函數之外定義的變數,從定義處開始到檔案結束均有效,當然可以使用extern修飾將其範圍擴大到其他檔案。
特點:如果局部變數和全域變數同名,那麼在局部變數作用範圍內外部變數不起作用;在不必要是盡量不要使用全域變數,因為其降低了函數的通用性。
2、實驗
另外加上static和const關鍵字之後,這些變數又是怎麼儲存的呢?下面的代碼在linux系統調試通過:
#include <stdio.h>#include <stdlib.h>#include <unistd.h> int int_a=1; static int static_int_a=2; const int const_int_a=3;int main (){ int int_b=1; static int static_int_b=2; const int const_int_b=3; int *p1=malloc(4); printf(" int_a: %p\n",&int_a); printf("static_int_a: %p\n",&static_int_a); printf(" const_int_a: %p\n",&const_int_a); printf(" int_b: %p\n",&int_b); printf("static_int_b: %p\n",&static_int_b); printf(" const_int_b: %p\n",&const_int_b); printf(" p: %p\n",&p1); printf(" main: %p\n",main); printf("%d\n",getpid()); while (1);}
是調試結果:
是程式運行時的maps檔案:
3、結果
通過上面的代碼實驗可以看出
1、 普通全域變數和static修飾的全域變數存放在全域區(程式運行時把這些資料存進棧中),但是const修飾的全域變數存放在代碼區(程式運行時該資料存在唯讀Memory中)。
2、 普通局部變數和const修飾的局部變數存放在棧裡面,但是static修飾的存放在了全域區。
4、雜記
一、const修飾符
1.修飾的變數必須初始化:
const int i=1;//合法 const int j;//非法
2.被修飾的變數只能被讀:
const int i=1; int j=2; i=j;//非法 j=i;//合法
3.可以避免不必要的記憶體配置:
#define STR "abcdef" const char str[]="abcdef"; printf(STR);//為STR第一次分配記憶體 printf(str);//為str一次分配記憶體 printf(STR);//為STR第二次分配記憶體 printf(str);//已經不需要分配記憶體了
同樣是一個常量字串,宏定義在編譯時間候自動替換了,所以實際是很多的常量。
4.數值常量和指標常量區分:
int x=1; const int y=2; //y是常量,初始化之後就不能修改y值了 const int *p1=&x; //p1指向的內容是常量,不可以修改 int * const p2=&x; //指標p2是常量,所指向的內容可修改 const int * const p3=&x;//指標p3和p3指向的內容均不可以修改 p1=&y;//合法 *p2=3;//合法
5.const的常量未必一定不可以修改
const int x=1; int *p=(int*)&x; *p=2;// 此時的x的值便被修改為2了
C語言各種變數儲存方式