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

2025-03-10 09:28:27
推荐回答(2个)
回答1:

可以使用变长数组或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); /* 把分配的内存释放掉 */ }

求采纳

回答2:

#
include"stdio.h"
#
include"malloc.h"
int
main(
void)
{int
len,i;
int
*
temp;
printf(
"请输入数组的长度:");scanf("%d"
,&len);temp=(
int
*)malloc(
sizeof(int
)*len);printf("请输入数组的元素:\n");for(i=0;i<len;i++
){scanf("%d",&temp[i]
);
}return
0;
}用手机写,没调试,有错别见怪。