当我们创建一个未知大小的数组时,我们使用malloc()
函数。
这是我想从用户那里获取数组大小作为输入时的代码。
int* ptr, len;
printf("Please enter the size number:");
scanf_s("%d", &len);
ptr = (int*)malloc(len * sizeof(int));
for (int i = 0; i < len; i++)
{
printf("Enter the %d. number: ", i+1);
scanf_s("%d", ptr + i);
}
但这就是问题 我想构建一个应用程序,其中用户不指示任何大小值并输入数字,以便将它们放入数组中。数组已满,但没有任何限制。它最初没有像我上面的代码那样分配任何内存。唯一的限制是用户输入特定数字(例如-5),然后阵列将停止。并打印出值。
本质上:我正在寻找内存分配,但分配将根据特定的用户输入决定。
无限地运行代码且从不显示数组的 Realloc 编辑
int i = 0,ctr=0;
int* ptr = (int*)malloc(sizeof(int));
do
{
printf("Enter the %d. value: \n",i+1);
scanf_s("%d", ptr + i);
ctr += 1;
ptr = (int*)realloc(ptr, (i + 2) * sizeof(int));
i += 1;
} while (*(ptr+i)!=-1);
最佳答案
这对我有用。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,n;
ptr = (int *)malloc(sizeof(int)); //
int i = 0;
while(1)
{
puts("Enter a number");
scanf(" %d",&n);// Take the value
if(n == -5) //
{
*(ptr + i) = n; //if you don't wish to add -5 to your array remove this
// statement and following i++
i++;
break;
}
else
{
*(ptr + i) = n;
ptr = realloc(ptr,(i+2)*sizeof(int));// reallocating memory and
// passing the new pointer as location in memory can
// change during reallocation.
i++;
}
}
int end = i;// Saving the number of elements.
for(i=0;i<end;i++)
printf(" %d\n",ptr[i]);
return 0;
}
关于arrays - 有没有办法在用户输入特定数字之前创建数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67149213/