arrays - 有没有办法在用户输入特定数字之前创建数组?

标签 arrays c loops dynamic-memory-allocation realloc

当我们创建一个未知大小的数组时,我们使用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/

相关文章:

c - Do-while 循环 - 终止条件有什么问题?

PHP将用户数组插入用户数组并循环用户和用户数据(属性)

c - 如何使用冒泡排序并对带有字符串的二维数组进行排序

arrays - 最长 K 序贯递增子序列

.net - 我有 3 种方法来获取数组的 ubound

c - 如何从 C 文件中获取分离的整数

c++ - 在 QtCreator IDE 中将 Octave 与 C++ 集成

javascript - $.each 函数添加返回到外部变量

arrays - HTTP GET 无休止地请求数据

c - 如何使 C 编译器将所有嵌套循环转换为单个循环