顯示具有 C 標籤的文章。 顯示所有文章
顯示具有 C 標籤的文章。 顯示所有文章

2011年2月7日 星期一

[C]malloc 與 free 使用

int *ptr_i;
ptr_i = (int *)malloc(sizeof(int));

/*沒配置到記憶體結束程式*/
if (ptr_i == NULL) {
  printf("function malloc can't alllocate memory!\n");
  system("PAUSE");
  return 0;
}

*ptr_i = 5; /*設定i值

free(ptr_i); /*釋放 ptr_i 所指向的空間 */
ptr_i = NULL; /*制定 ptr_i 為 NULL */

system("PAUSE");
return 0;

2011年1月10日 星期一

[C]union記憶體共用

#include<stdio.h>

union data
{
   char a;
   int b;
}

main()
{
   union data test;

   test.b = 0;
   printf("test.a = %c, test.b = %d\n", test.a, test.b);

   test.b = 'X';
   printf("test.a = %c, test.b = %d\n", test.a, test.b); /* 由於 union 共用記憶體,雖然只有 test.b 被修改 ,test.a 也會受到影響。 */
                                                         /* ps. X 的 ASCII 碼為 88 */
}

[C]常用函式表


函式名所需之標頭檔簡便使用方法備註
printf()stdio.hprintf("字串", 參數... )列印函式
scanf()stdio.hscanf("字串", 參數... )鍵盤輸入函式,請注意 "&"
pow()math.hpow(x, y)x 的 y 次方,傳回值為 double
floor()math.hfloor(x)取小於 x 的最大整數,x為double,如:floor(3.14)=3。
ceil()math.hceil(x)取大於 x 的最小整數,如:ceil(3.14)=4。
sqrt()math.hsqrt(x)把 x 開根號
strlen()string.hstrlen(字串的名字)計算字串資料的長度。
strcmpstring.hstrcmp(字串1, 字串2)比較兩個字串的異同。傳回值為 0 時,兩字串相同;反之,則不相同。
strcpystring.hstrcpy(字串1, 字串2)將字串2 拷貝一份到字串1。 原來在字串1 的資料將會覆蓋而消失。



2011年1月9日 星期日

[C]for迴圈使用

  1. int i;  //需在外宣告
  2. for (i = 0; i < 10; i++) {
  3.   printf("%d", i);
  4. }
output 123456789

2011年1月8日 星期六

[C]基本輸出型態

%c以字元 方式輸出
%d10 進位整數輸出
%o以8進 位整數方式輸出
%u無號整數輸出
%x, %X將整 數以16進位方式輸出
%f浮點 數輸出
%e, %E使用科學記號顯示浮點數
%g, %G浮點數輸出,取%f或%e(%f或%E),看哪個表示精簡
%%顯示 %
%s字串輸出