#include <stdio.h>
#include <math.h>
int main()
{
int i = 0, num[10], termnum = 0;
return 0;
}
大家好,我正在尝试计算平均值并接受用户的数字。 我想存储索引以将信息用于其他用途。 因此,用户可以将数字放到&#34; -1&#34;然后停止 我可以调整阵列吗?
例如int num[i],i=0;
?
答案 0 :(得分:3)
如果您知道数组大小在运行时已知并且相当小,则可以使用可变长度数组。
size_t len;
scanf("%zu", &len);
int arr[len];
VLA的问题在于无法捕获分配失败。例如,如果len
非常大,那么arr
分配可能会失败,并且在它爆炸之前您不会知道它。此外,自C11以来,VLA支持是可选的。
但是如果你想在不知道总数的情况下连续输入数字,那么你可以根据需要使用malloc
和realloc()
分配动态内存:
size_t n = 16; //arbitrary start size
int *arr = arr(n * sizeof *arr);
while(..) {
//read input here
// realloc "arr" if number of inputs go beyond "n"
}
另一方面,如果您不需要这些数字但只对平均数感兴趣,那么您根本不需要任何数组。只需阅读数字并在阅读时计算总数:
int total = 0;
int num = 0;
size_t n = 0;
while(scanf("%d", &num) == 1) && num != -1) {
total += num; // need to take care of integer overflow!
n++;
}
答案 1 :(得分:0)
阵列(包括可变长度数组)在定义后无法调整大小。
如果您希望存储可以根据需要增长或缩小,则必须使用malloc
,calloc
或realloc
之一动态分配,然后使用{ {1}}:
realloc
每次加倍存储是一种常见的技术;它最大限度地减少了int *arr;
size_t arrSize = 10; // current size of array
size_t itemsRead = 0; // number of elements stored so far
/**
* Initially set aside space to store 10 integers
*/
arr = malloc( sizeof *arr * arrSize );
...
int item;
while ( scanf( "%d", &item ) == 1 && item != -1 )
{
if ( itemsRead == arrSize )
{
int *tmp = realloc( arr, sizeof *arr * (arrSize * 2) );
if ( tmp )
{
arr = tmp;
arrSize *= 2;
}
else
{
// could not extend storage, handle as necessary
}
}
arr[itemsRead++] = item;
}
次呼叫的数量(这可能很昂贵)。如果您愿意,您可以每次延长固定金额。
realloc
如果无法满足请求,将返回realloc
,因此您应将结果存储到临时变量中;否则你可能会失去对已经分配的内存的引用,从而导致内存泄漏。
答案 2 :(得分:0)
相当简单的人。如果使用malloc
函数作为参数lenght*sizeof(//type)
传递,则可以在HEAP内存中获得所需的空间。 malloc
返回指向已分配内存开头的指针。
int length;
int *pointer;
//read the length
pointer=malloc(length * sizeof(int));
指针以void的形式返回,因此您需要根据需要进行强制转换。