C语言中我要定义一个数组,可是这个数组的元素的个数要根据我输入的元素的个数来确定 该怎么做。

即我输入3个数,数组大小为3;输入6个数,数组大小为6.动态分配做不到,望给出详细的程序。

由于空格和回车都用来分割数字了,所以以任何非数字字符作结束。供参考……

//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int *myarray(int *p,int *la){
    unsigned N = sizeof(int)==4 ? 0xFFFFFF : 0xFFFF,i;
    int lc,*q=(int *)malloc((lc=sizeof(int))*N);
    if(!q){
        printf("Failure to apply for a temporary space...\n");
        return NULL;
    }
    for(i=0;;i++)
        if(scanf("%d",q+i)!=1)
            break;
    if((p=(int *)malloc(lc*i))==NULL){
        printf("Apply for actual use of space to fail...\n");
        return NULL;
    }
    memcpy(p,q,lc*i);
    free(q);
    *la=i;
    return p;
}
int main(void){
    int *p=NULL,n,i;
    printf("Please enter the array element value(Any letter end)...\n");
    if(p=myarray(p,&n)){
printf("You enter %d element(s), so the array length is %d.\n",n,n);
for(i=0;i<n;printf("%d ",p[i++]));
free(p);
}
else printf("Input failed...\n");
    printf("\n");
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-29
int p[];
int len;
scanf("%d",&len);
p=(int*)malloc(sizeof(int)*len);//这里,int 是 int p[]; 的int,如果是char p[]; 这里的int全部换成char, len的数据类型就是int,不用换。
//具体的可以用百度搜索
//在后面, p就是数组了,元素个数就是len个追问

scanf("%d",&len);元素个数就是len由键盘输入,问题是我事先不能规定输入元素的个数

追答

电脑打不开网页

相似回答