2012-08-23 35 views
2

我試圖創建一個由一些字母和數字組成的字符數組(函數最初的方式更復雜,但我不停地簡化它以找出它爲什麼不能正常工作)。所以我有一個字符數組,我把2個字符,並嘗試添加一些數字。 由於我無法弄清楚的原因,數字不會被添加到數組中。這可能真的很愚蠢,但我是C新手,所以這裏是簡化的代碼。任何幫助非常感謝,謝謝!嘗試將一些數字放入字符數組

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

char some_string[20]; 

char *make_str() { 
    some_string[0] = 'a'; 
    some_string[1] = 'x'; 
    int random = 0; 
    int rand_copy = 0; 
    random = (rand()); 
    rand_copy = random; 
    int count = 2; 
    while (rand_copy > 0) { 
    rand_copy = rand_copy/10; 
    ++count; 
    } 
    int i=2; 
    for (i=2; i<count; i++) { 
    some_string[i] = random%10; 
    random = random/10; 
    } 
    return (some_string); 
}  

int main(int argc, const char *argv[]) { 
    printf("the string is: %s\n",make_str()); 
    return 0; 
} 
+0

任意數量小於32(如果我沒記錯)對應於一個非打印字符 – Saphrosit

+0

@axesdenied短故事人物:有沒有這樣的事情在信一臺電腦。一切都是二進制數字。 char類型也不例外。當你寫'some_string [0] ='a';'你實際上正在寫'some_string [0] = 97;'時,字符文字比原始ASCII碼更容易閱讀。 'random%10'給出一個介於0到9之間的數字。ASCII數字的數字在48('0')和57('9')之間。在這裏輸入+'0',實際上意思是「給我一個0-9之間的隨機數,然後加48」,這相當於「給我一個48到57之間的隨機數。」 – Lundin

回答

2

你有很多問題:

  1. 得到的字符串不是零終止。添加some_string[i] = '\0';來解決這個
  2. 字符(char)大概是「字母」,但random % 10產生其當轉換爲在控制代碼字符的結果(ASCII字符0-9是控制碼)的數(int)。你最好使用some_string[i] = (random % 10) + '0';
  3. 你正在使用固定長度的字符串(20個字符),這可能是足夠的,但它可能會導致很多問題。如果你是一個初學者,並沒有學習動態內存分配,那麼現在就可以了。但請記住,固定長度緩衝區是錯誤C代碼的十大原因之一。如果你必須使用固定長度的緩衝區(這樣做有合理的理由),ALLWAYS會檢查你是否超出緩衝區。爲緩衝區長度使用預定義的常量。
  4. 除非練習的要點是嘗試將數字轉換爲字符串,否則使用libc函數(如snprintf)將任何內容打印到字符串中。
  5. 不使用全局變量(some_string),如果你這樣做(對於一個小例子來說可以),返回這個值沒有意義。

稍微好一點的版本:

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

#define BUF_LENGTH 20 
char some_string[BUF_LENGTH]; 

char *make_str() { 
    some_string[0] = 'a'; 
    some_string[1] = 'x'; 
    int random = rand(); 
    int rand_copy = random; 
    int count = 2; 
    while (rand_copy > 0) { 
     rand_copy = rand_copy/10; 
     ++count; 
    } 
    int i; 
    for (i = 2; i < count; i++) { 
     /* check for buffer overflow. -1 is for terminating zero */ 
     if (i >= BUF_LENGTH - 1) { 
      printf("error\n"); 
      exit(EXIT_FAILURE); 
     } 
     some_string[i] = (random % 10) + '0'; 
     random = random/10; 
    } 
    /* zero-terminate the string */ 
    some_string[i] = '\0'; 
    return some_string; 
}  

int main(int argc, const char *argv[]) { 
    printf("the string is: %s\n",make_str()); 
    return 0; 
} 
+0

「固定長度緩衝區是一個,但是動態內存泄露在前10名列表中甚至更高,靜態緩衝區的大小在程序員開始一些大腦活動之後是相當安全的,如果有範圍檢查,甚至會更安全並在程序中進行健全性檢查,因爲應該是這樣的。 – Lundin

+0

固定長度與內存分配無關。您可以輕鬆編寫'char * buf [20];'您可以編寫'char * buf =( char *)malloc(20);'。 –

+0

它與內存分配有關,因爲靜態數組不能具有可變長度(除非它們是VLA)btw你可能意味着'char buf [20];''和' char * buf = malloc(20);'。 – Lundin