你的“控制他的个数”是哪个他? 你是说自动增加 动态分配的单元个数 吗?
预先不知道个数,一边输入一边增加 动态分配的单元个数, 可以用 realloc 函数。
例如,你不断输入数据,不断 增加 动态分配的单元个数,直到 输入数 为 0 时 操作结束,
程序如下:
#include
#include
int main ()
{
int input,n;
int count = 0;
int* numbers = NULL;
int* more_numbers = NULL;
do {
printf ("Enter an integer value (0 to end): ");
scanf ("%d", &input);
count++;
more_numbers = (int*) realloc (numbers, count * sizeof(int));
if (more_numbers!=NULL) {
numbers=more_numbers;
numbers[count-1]=input;
}
else {
free (numbers);
puts ("Error (re)allocating memory");
exit (1);
}
} while (input!=0);
printf ("Numbers entered: ");
for (n=0;n
return 0;
}
你要的功能可以实现,但 程序较复杂。
你不如 开个 足够大的 数组,程序可以简单很多。
虽然不知道你想干什么,希望这例子可以帮助到你
#include
#include
int main()
{
int *a,n,i;
scanf("%d",&n);
a=calloc(n,sizeof(int));
for(i=0;i{
scanf("%d",&a[i]);
printf("%d ",a[i]);
}
free(a);
return 0;
}
采用指针运算就行了,给第几个赋值就在指针p的基础上加上几,比如要个第五个赋值,scanf输入时使用p+4就可以了。
不能一次赋几个,只能一次赋1个值,一次赋多个值是不可能的,可以通过循环一次赋1个,从而达到赋几个的目的