問題1:#define到底存在程序的哪個區?
自己寫了一個小程序驗證一下第一個問題。
程序代碼:
<span style="font-size:18px;">#include <stdio.h>#include <STDLIB.H>#define kMAX 100typedef struct { int ID; char * name;}Student;void test(){ return;}
//常量區,靜態區,堆區,棧區,程序代碼區
const int a = 100;char * b = "ok123";int main(){ Student stu = {10,"張三"}; int n = 9999; int *p = &n; int num[10] = {1,2,3,4}; int *ap=(int*)malloc(100*sizeof(int));//動態分配內存 static int k = 9; printf("常量區/n"); printf("const int(%p)/n",&a); printf("char *(%p)/n",b); printf("靜態區/n"); printf("static int (%p)/n",&k); printf("堆區/n"); printf("(int*)malloc(100*sizeof(int))(%p)/n",ap); printf("棧區/n"); printf("struct int(%p),struct char *(%p)/n",&stu.ID,&stu.name); printf("int [](%p)/n",num); printf("int *(%p)/n",&p); printf("int(%p)/n",&n); printf("程序代碼區/n"); printf("test()(%p)/n",test); printf("未知/n"); printf("define (%p)/n",kMAX); free(ap); return 0;}</span>
發現:
1、通過運行代碼可以看出程序的幾個內存區互不相鄰;
2、#define的內存單元在程序運行前已經分配。
3、我們知道,char *會存在常量區,但如果我們把char *“封裝”到一個struct里,這時它會同該struct分配到棧區中,也就是說,我們可以修改struct中char *里的值。
----------------------------------------------------------------------------------------------------------------------------------------------------------
問題2:我們已經知道,宏實質上是替換,而函數是傳參,調用。那么,帶參數宏與普通函數在效率上有什么區別?
通過查閱一些資料了解到
1、普通函數是在程序運行時調用,程序會給它的成員分配內存。而帶參宏是在編譯前就已經執行,并且不會分配內存單元。
2、宏替換不占用運行時間,只占用編譯時間。函數則占用運行時間。所以,如果想提高程序運行效率,可以用宏代替部分函數。
新聞熱點
疑難解答
圖片精選