第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();
}本回答被网友采纳