2014-03-19 27 views
0

我不是很在經歷C.我想有一些代碼,是這樣的:如何使一個字符串數組用C

字符串數組申報;

功能是清除字符串 的陣列並插入一個新的組字符串(數量不詳)

我怎樣才能做到這一點?我知道我可以做const char *a[2];,但是當我聲明它時需要輸入一個數組大小。我可以爲我的字符串數組創建一個可支持多種大小的變量嗎?

+0

您正在使用哪個版本的C? C99? –

回答

4

您可以使用指針指針。

char **strings; 

這裏是你將如何創建它:(其中<size>是數組的大小)

strings = malloc(sizeof(char*) * <size>); 

現在設置/獲取的元素很簡單:

strings[0] = "hello"; 
printf("%s", strings[0]); 

只是一個警告,內存尚未設置爲完全空字符串。如果你希望所有的字符串是默認爲空,然後使用calloc()代替malloc()

strings = calloc(sizeof(char*) , <size>); 
+2

這將使所有指向字符串的指針爲NULL,而不是使所有字符串NUL終止。如果您取消引用它們,則會發生段錯誤,而不會獲得空字符串。 – Emmet

+0

所以,如果我把「strings = malloc ...」行放在函數中,我可以多次調用它並讓它清空數組嗎?技術上, –

+0

是的,這就是malloc所做的,但更聰明的方法就是遍歷所有元素並將它們設置爲「」。實際上,如果你只是想重新填充數組,那麼你可能只需要替換元素,然後將其餘元素設置爲「」。讓我知道,如果這太混亂,如果這樣,然後生病編輯解釋它 – ASKASK

0

您可以控制數組的大小是這樣的:

int size; 
    char *a[size]; 
    printf("enter size"); 
    scanf("%d",&size); 
0

你必須使用一個char**,指針指向char,以便捕獲一個動態的字符串數組。

如果你要10串,你必須使用:

char** strings = (char**)malloc(sizeof(char*)*10); 

要存儲一個字符串數組的第一個元素,你必須使用:

strings[0] = malloc(strlen("abcd")+1); 
strpcy(strings[0], "abcd"); 

這裏有一個程序,演示了整個事情:

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

int main() 
{ 
    char string[200]; 
    char** strings = NULL; 
    int numStrings = 0; 
    int n = 0; 
    int i = 0; 

    /* Read the number of strings */ 
    do 
    { 
     printf("Enter the number of strings (0 or higher): "); 
     n = scanf("%d", &numStrings); 
    } while (n != 1 || numStrings < 0); 

    /* Eat up the remaining characters afte the integer */ 
    fgets(string, 199, stdin); 

    if (numStrings > 0) 
    { 
     /* Read the strings */ 
     strings = (char**)malloc(numStrings*sizeof(char*)); 
     for (i = 0; i != numStrings; ++i) 
     { 
     printf("Enter a string: "); 
     fgets(string, 199, stdin); 
     strings[i] = malloc(strlen(string)+1); 
     strcpy(strings[i], string); 
     } 

     /* Print the strings back */ 
     for (i = 0; i != numStrings; ++i) 
     { 
     printf("%s", strings[i]); 
     } 

     /* Now release the memory back to the system */ 

     /* First the individual strings */ 
     for (i = 0; i != numStrings; ++i) 
     { 
     free(strings[i]); 
     } 

     /* Now the array */ 
     free(strings); 
    } 

    return 0; 
} 
+0

這部分是不必要的複雜。例如「存儲字符串」部分可以是:'strings [0] =「abcd」;'它既快又短 – ASKASK

相關問題