包青天之紫金锤:c语言如何申请一个由外部输入长度的数组?

来源:百度文库 编辑:高校问答 时间:2024/04/20 09:23:08
先由外部输入一个量,再以此作为长度定义一个数组,可以实现吗?怎样做?谢谢

动态分配内存

#include<stdlib.h>
int main()
{
int n,*p;
int i;
printf("Please input the num:");//输入数组的长度
scanf("%d",&n);
p=(int *)malloc(sizeof(int)*n);//定义动态数组
printf("Please input the numbers:");
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
for(i=0;i<n;i++)
{
printf("%5d\n",p[i]);
}
getchar();
}

可以使用malloc函数实现。
1 头文件:
stdlib.h
2 声明:
void *malloc(size_t length);
3 功能:
申请一段长度为length字节的内存空间,并将首地址返回。
4 示例:
如元素类型为type,输入的数组长度存在变量n中,那么要申请的数组所占空间为sizeof(type)*n。
数组需要定义为指针形式
type *p;
申请代码为
p = (type*) malloc(sizeof(type)*n);

由外部输入长度的数组,
这句话的意思就是说数组内存是活动的,因此需要用calloc或者malloc
int main(){
char *str;
int size;
scanf("%d",&size);//外部输入长度
str = (char*)calloc(size,sizeof(char));
free(str);
}

int a[100];
main()
{int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
printf("%d",a[i]);
getch();}
先定义较大长度的数组,取其中部分来操作。

C++可以
它支持动态数组
例如,
int *a;
// get n from input
a = new int [n];
//a[n] as an array of n elements