[英]Is there any way to create an array until user enters a specific number?
當我們創建一個大小未知的數組時,我們使用malloc()
function。
這是我想從用戶那里獲取數組大小作為輸入的代碼。
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);
}
但這是我想要構建一個應用程序的問題,其中用戶不指示任何大小值並輸入數字以便將它們放入數組中。 數組正在填充,但沒有任何限制。 它最初沒有像我上面的代碼那樣分配任何 memory 。 唯一的限制是用戶輸入一個特定的數字(比如-5),然后陣列被停止。 並打印出值。
本質上:我正在尋找 memory 分配,但分配將取決於特定的用戶輸入。
無限運行代碼並且從不顯示數組的 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;
}
您可以使用標准的 function realloc
或定義一個列表。 在最后一種情況下,對列表元素的訪問將是 sequantil。
這是一個演示程序,展示了如何使用 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 );
}
程序 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
請注意,您可能不會在 realloc 調用中使用相同的指針,例如
int *p = realloc( p, ( n + 1 ) * sizeof( *p ) );
因為通常 function realloc
可以返回 null 指針。 在這種情況下,由於將指針p
重新分配為 null 指針,已分配的 memory 的地址將丟失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.