我想在数组中包含来自用户的一些整数值/字符串值,并且不确定数组将会变长多长时间。如果我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;
}
使用new和delete来动态分配数组很好吗? – lakesh 2012-02-19 12:29:43
@lakesh只有当你使用C++时:-)你标记了问题'c',你的代码看起来真的是c-ish。 – cnicutar 2012-02-19 12:30:37
感谢您的澄清。我编辑了上述问题的答案。现在好点了吗?任何更正? – lakesh 2012-02-19 12:40:18