2012-02-19 143 views
0

我想在數組中包含來自用戶的一些整數值/字符串值,並且不確定數組將會變長多長時間。如果我intitalise像數組[500],我知道這是一個糟糕的解決方案和糟糕的編程技巧..我該如何改進?在程序運行時調整/調整數組的大小的最佳方法

示例代碼如下:

int main(void){ 
    int t=0; 
    char str[200]; 
    int count[20]; 
    printf("Please enter the number of test cases(between 1 to 20):"); 
    scanf("%d",&t); 
    for (int i = 1; i<=t;i++) 
    { 
     printf("Please enter each of %i test case values:",i); 
     gets(str); 
     //set_create(str); 
     printf("\n"); 
    } 
    for(int i = 0;i<t;i++) 
    { 
     prinf("%i",count[i]); 
     printf("\n"); 
    } 
    return 0; 
} 

上面的代碼是錯誤的肯定。需要一些幫助來提高代碼...感謝

編輯的代碼:

int main(void){ 
     int T=0; 
     int *count; 
     printf("Please enter the number of test cases(between 1 to 20):"); 
     scanf("%d",&T); 
     count = malloc(T * sizeof *count); 
     for (int i = 1; i<=T;i++) 
     { 
      printf("Please enter each of %i test case values:",i); 
      fgets(count); 
      printf("\n"); 
     } 

     return 0; 
    } 

回答

4

只需使用根據需要指針和malloc/realloc內存。不要使用gets - 這是不安全的,不再符合標準。改爲使用fgets

例如,如果你不知道你有多少count元素需要:

int *count; 

scanf("%d", &t); 
count = malloc(t * sizeof *count); 
+0

使用new和delete來動態分配數組很好嗎? – lakesh 2012-02-19 12:29:43

+0

@lakesh只有當你使用C++時:-)你標記了問題'c',你的代碼看起來真的是c-ish。 – cnicutar 2012-02-19 12:30:37

+0

感謝您的澄清。我編輯了上述問題的答案。現在好點了嗎?任何更正? – lakesh 2012-02-19 12:40:18

1

在這種情況下,你可以爲數組中的堆與功能malloc/calloc或堆棧功能alloca()上分配內存(在標題"alloca.h");

相關問題