数组问题(c语言),如何让输入者定义个数,并输入数值,形成数组

. 比如用户输入5,然后再输入5个数字,就成了数组...麻烦详细点..谢谢...

严格意义上讲,c语言里面定义数组时其长度不能为变量,必须为固定值,因为c语言程序在定义数组时,必须先给数组开辟一个内存空间。不过,你所提的要求还是可以实现的,一般的做法是,可以先假设一个较大的数(不超过你所想输入的输入的数组长度的最大值MXLENGTH,)作为初始定义时数组大小,然后在输入数组时,在程序中设置判断语句,判断已输入长度是否到达用户所要输入的长度,若已到达则结束输入。
#include<stdio.h>
#define MAXLENGTH 1000
void main()
{
int A[MAXLENGTH];
int i,n;
printf("please input the length of array:\n");
scanf("%d",&n);
printf("input the array:\n");
for(i=0;i<=n-1;i++)
scanf("%d",&A[i]);
printf("now the array is below:\n");
for(i=0;i<=n-1;i++)
printf("%d ",A[i]);
}
根据提示先输入所要输入数组大小,回车之后依次输入数组各元素值,以空格作为数组元素间间隔,不要超过你刚才输入的长度,不然会报错。如果所用软件是visual c++,可以给为中文提示输入!
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-09-07
只能采用动态分配空间的方式,即:采用指针的方法去动态的定义数组空间。
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main( void )
{
int i=0;
int nsize=0;
int *pstr=NULL ;

scanf("%d",&nsize);

if( nsize <=0 )
{
printf("size must greater than 0!\n");
return -1;
}

pstr=malloc( nsize );
if ( pstr == NULL )
{
printf("malloc error!\n" );
return -1;
}

for ( i=0;i<nsize;i++ )
{
scanf("%d", pstr+i );
}

for ( i=0;i<nsize;i++ )
{
printf("%d\n", *(pstr+i) );
}

free(pstr); //一定要记得去释放指针,否则,在写后台程序(常驻内存的程序)时,会造成内存碎片产生。
return 0;
}
第2个回答  2019-06-10
可以使用变长数组或malloc函数动态分配内存。
变长数组:
#include
void
array_show(const
int
);
int
main(void)
{
int
rows;
puts("输入数组大小:
");
scanf("%d",
&rows);
array_show(rows);
return
0;
}
void
array_show(const
int
cols)
{
int
array[cols];
…………
…………
}
malloc函数动态分配内存:
#include
#include
void
array_show(const
int);
int
main(void)
{
int
rows;
puts("输入数组大小:
");
scanf("%d",
&rows);
array_show(rows);
return
0;
}
void
array_show(const
int
cols)
{
int
count;
int
*
point
=
(int
*)malloc(sizeof(int)
*
cols);
for(count
=
0;
count
<
cols;
cols++)
{
scanf("%d",
&point[count]);
}
…………
…………
free(point);
/*
把分配的内存释放掉
*/
}
求采纳
第3个回答  2011-09-09
第一种方法数组内容自定义
#include <stdio.h>
main()
{ int a[10],n,i;
scanf("%d",&n);
for(i=0;i<10;i++)scanf("%d",&a[i]);
for(i=0;i<10;i++)if(n==a[i])break;
if(i==10)printf("no found"); else printf("%d",i);
system("PAUSE");
}
第二种方法数组内容已定义
#include <stdio.h>
main()
,n,i;
scanf("%d",&n);
for(i=0;i<10;i++)if(n==a[i])break;
if(i==10)printf("no found"); else printf("%d",i);
system("PAUSE");
}
第4个回答  2011-09-07
//先输入一个正整数作为你的数组大小,然后再定义数组,程序如下:

#include <stdio.h>

main()
{
int i,n;

printf(" How many numbers would you like to enter ? "); //输入数组大小
scanf(" %d",&n);

int N[n]; //通过正整数n定义数组N的大小

for(i=0;i<n;i++) //输入数组N数据
{
printf("\n Please enter the %d number: ",i+1);
scanf("%d",&N[i]);
}
getchar();
printf("The numbers you enter:\n"); //数组输出到屏幕
for(i=0;i<n;i++)
printf(" %d ",N[i]);

getchar();
}本回答被网友采纳
相似回答