【问题标题】:Is there any way to create an array until user enters a specific number?在用户输入特定数字之前,有什么方法可以创建数组?
【发布时间】:2021-07-12 21:29:54
【问题描述】:

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

【问题讨论】:

  • 您可以使用 realloc 重新分配一个数组。另一种方法是使用列表。但在最后一种情况下,您将只能按顺序访问列表中的元素。
  • 我尝试使用 realloc 进行编程,但即使我给它一个条件,循环也会无限运行。
  • 它无限期地运行,因为您的while 条件会查看尚未输入的数字,因为您在它之前增加了i
  • 考虑使用链表。
  • @EmanuelP 当我看到它时,我笑得很厉害。好的,谢谢先生。就是这样。

标签: arrays c loops dynamic-memory-allocation realloc


【解决方案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;
}

【讨论】:

  • 非常简单,易于理解。谢谢你。此外,我的代码实际上也是正确的,但由于“i”语句拼写错误,我无法得到结果。
  • @Belgrad,是的,我注意到了,但想给你一些不言自明的东西。一个建议,尝试使用 cmets 来描述你在做什么。从短期和长期来看,这将有助于解决这些小错误。并尝试阅读此ericlippert.com/2014/03/05/how-to-debug-small-programs
  • 我永远无法放弃询问组织不当的帖子 :) 我总是试图找到正确的方式向大家提出问题,但每次我问我都会收到非常愤怒的反馈。感谢这篇博文,它会对我有所帮助。
【解决方案2】:

您可以使用标准函数realloc 或定义一个列表。在最后一种情况下,对列表元素的访问将是 sequantil。

这是一个演示程序,展示了如何使用函数realloc 输入以标记值结尾的数字序列。

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    int *p = NULL;
    size_t n = 0;

    int allocation_failed = 0;
    const int Sentinel = -1;

    printf( "Enter a sequence of values (%d - exit): ", Sentinel );

    for (int value; !allocation_failed         &&
                    scanf( "%d", &value ) == 1 &&
                    value != Sentinel; )
    {
        int *tmp = realloc( p, ( n + 1 ) * sizeof( *p ) );

        if (!( allocation_failed = tmp == NULL ))
        {
            p = tmp;
            p[n++] = value;
        }
    }

    for (size_t i = 0; i < n; i++ )
    {
        printf( "%d ", p[i] );
    }

    putchar( '\n' );

    free( p );
}

程序输出可能看起来像

Enter a sequence of values (-1 - exit): 0 1 2 3 4 5 6 7 8 9 -1
0 1 2 3 4 5 6 7 8 9

请注意,您不能在调用 realloc 时使用相同的指针,例如

int *p = realloc( p, ( n + 1 ) * sizeof( *p ) );

因为通常函数realloc 可以返回一个空指针。在这种情况下,由于重新分配指针p,已分配内存的地址将丢失,将变为空指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多