2012-02-19 39 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");

相关问题