简体   繁体   English

在用户输入特定数字之前,有什么方法可以创建数组?

[英]Is there any way to create an array until user enters a specific number?

When we create an array with unknown size then we use malloc() function.当我们创建一个大小未知的数组时,我们使用malloc() function。

Here is the code when I want to take the array size from user as an input.这是我想从用户那里获取数组大小作为输入的代码。

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);
    }

But here is the question I want to build an application where user doesn't indicate any size value and enters the numbers so that place them into an array.但这是我想要构建一个应用程序的问题,其中用户不指示任何大小值并输入数字以便将它们放入数组中。 Array is filling but hasn't got any limits.数组正在填充,但没有任何限制。 It hasn't allocated any memory initially like my code above.它最初没有像我上面的代码那样分配任何 memory 。 Only limit is that user enters a specific number (say -5) then, array is being stopped.唯一的限制是用户输入一个特定的数字(比如-5),然后阵列被停止。 And prints out the values.并打印出值。

In essence: I am looking for memory allocation but allocation will be decided on specific user input.本质上:我正在寻找 memory 分配,但分配将取决于特定的用户输入。

Realloc edit that runs the code infnitely and never displays the array无限运行代码并且从不显示数组的 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);

This worked for me.这对我有用。

#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;
}

You can use the standard function realloc or define a list.您可以使用标准的 function realloc或定义一个列表。 In the last case the access to elements of a list will be sequantil.在最后一种情况下,对列表元素的访问将是 sequantil。

Here is a demonstrative program that shows how the function realloc can be used to enter a sequence of numbers terminated by a sentinel value.这是一个演示程序,展示了如何使用 function 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 );
}

The program output might look like程序 output 可能看起来像

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

Pay attention to that you may not use the same pointer in a call of realloc like for example请注意,您可能不会在 realloc 调用中使用相同的指针,例如

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

because in general the function realloc can return a null pointer.因为通常 function realloc可以返回 null 指针。 In this case the address of the already allocated memory will be lost due to reassigning the pointer p will a null pointer.在这种情况下,由于将指针p重新分配为 null 指针,已分配的 memory 的地址将丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 动态增长数组直到用户输入 0 - Dynamically growing array until user enters 0 需要输入数组直到用户输入0 JAVA - Need To Take Input To Array Until User Enters 0 JAVA 如何重复直到用户输入整数? - How to repeat until the user enters an integer? 如果用户从数组中输入数字,如何获取二维数组的索引 - How do i get the index of a 2D array if the user enters a number from the array 在 java 上输入字符串的 eOne Dimensional Array。 不知道如何让数组停止输入,直到用户输入“alldone” - eOne Dimensional Array with string input on java. Do not know how to make the array stop taking input until the user enters "alldone" 有什么办法可以只用索引号从数组中打印出特定元素吗? - Is there any way to print out an specific element from an array with just its index number? 用户输入不在字符串数组中的值时出错 - Error when the user enters values not in String Array 创建一个在用户输入“ 0”时停止的数组 - creating array that stops when the user enters “0” 用户输入一个整数,该整数将添加到数组中-Java - User enters a int, which is added to an array - Java C 程序将元素插入数组,直到用户输入 0 或更少的数字 - C program to insert elements into an array until user inputs a 0 or less number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM