....

2014年5月25日 星期日

[長知識] C語言 - 新手篇章 - 動態配置記憶體空間

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
//動態配置一塊記憶體空間,以byte為單位
// int *ptr = (int*)malloc(?byte);
int amount;
int i;

printf("輸入幾個int?");
scanf("%i", &amount);


// 配置記憶體,要釋放記憶體
int *ptr = (int*)malloc(sizeof(int)*amount);


for(i = 0; i<amount; i++){
printf("輸入第%i個:", i+1);
scanf("%i",ptr);
++ptr;
}
//畫記憶體位置看看~~~~~~
// 方法一
for(i =amount; i>0 ; i--){
// 如果寫成*(ptr+i)會超出原本記憶體
printf("%i", *(ptr-i));
}

printf("------------------\n");

//  方法二
// ptr先歸位,回到記憶體原本位置
ptr -= amount;
for(i =0; i<amount ; i++){

printf("%i", *ptr);
ptr++;
}

// 作記憶體釋放
free(ptr);

return 0;
}

沒有留言:

張貼留言