2015年7月16日 星期四

[C] assert

     
   維護(assertion)敘述


        當自己寫的函式庫要提供他人使用時,適當的利用維護敘述,可以建立安全的使用
        介面,避免他人因為使用不當,而造成不可預期的後果。
        C 語言有自己的維護函式- assert() ,使用方法如下:

           assert(total < 1000);

        當程式執行到該行時,若 total < 1000 則程式可以繼續執行;若
        total >= 1000 ,則會秀出維護錯誤訊息的字串,並結束程式。
        維護字串包含有:判斷式子、程式檔名及該行的行號。
       緊記使用前要引入前置檔 assert.h
   
--------------------------------------------------------------------------------------------------

   Advanced example:
 

  1. #include <stdio.h>
  2. #include <assert.h>
  3. #define TRUE 1
  4. #define FALSE 0
  5. int
  6. find_char( char **strings, int value )
  7. {
  8. assert( strings != NULL );
  9. /*
  10. ** For each string in the list ...
  11. */
  12. while( *strings != NULL ){
  13. /*
  14. ** Look at each character in the string to see if
  15. ** it is the one we want.
  16. */
  17. while( **strings != '\0' ){
  18. if( *(*strings)++ == value )
  19. return TRUE;
  20. }
  21. strings++;
  22. }
  23. return FALSE;
  24. }

[C] gets


gets與scanf 功能都是讀入字元,
但scanf不吃空白, 即如果輸入 "Lam with c",
scanf只會讀入"Lam" ,
遇到空白後的字一概不理;
相反地 , gets 可以讀入埋空白後面的字.


-----------------------------------------------
#include <stdio.h>
int main(void)
{
    char s[20];
    printf("請輸入連續的字元....\n");   
    gets(s);
    printf("剛剛輸入的字串: %s\n", s);
     
    return 0;
}

[C] 二維陣列(char)




1) you can use 2D char array in this way
char name[5][100];
each line in the 2D array is an array of char with size = 100
for(i=0;i<5;i++)  
{
    printf(" Enter a name which you want to register\n");  
    scanf("%99s",names[i]);
}
2) You can use array of pointers in this way
char *name[5];
each element in the array is a pointer to a string (char array). you have to assign each pointer in the array to a memory space before you call scanf()
for(i=0;i<5;i++)  
{
    names[i]=malloc(100);  
    printf(" Enter a name which you want to register\n");  
    scanf("%99s",names[i]);
}
3) if you compile with gcc and gcc version >2.7 then your scanf() can allocate memory by using "%ms" instead of "%s"
char *name[5];
for(i=0;i<5;i++)  
{
    printf(" Enter a name which you want to register\n");  
    scanf("%ms",&names[i]);
}

文章出處:http://stackoverflow.com/questions/17466563/two-dimensional-array-of-characters-in-c