当前位置:编程学习 > C/C++ >>

C语言数组下标问题。

我有想定义个数组,但是下标的数量我不知道,我需要用scanf接收不知道怎么解决。

答案:#include <malloc.h>
定义一个数组大小int size.
scanf(&size)

定义动态字符数组p.
char *p=(char *)malloc(size*sizeof(char));
然后可以用p[i]访问数组元素。

#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p=(int *)malloc(sizeof(int));//p相当于数组使用
int count=0;
int i=0;
int temp=0;
printf("请输入数据(0表示结束输入)!\n");
while(1)
{
printf("输入第%d个数据:",count+1);
scanf("%d",&temp);
if(temp==0)break;
else p[count++]=temp;
p=(int *)realloc(p,(count+1)*sizeof(int));//分配空间+1
}
for (i=0;i<count;i++)
{
printf("%d  ",p[i]);
}
printf("\n");
}
这个好像是不可以的!但是我记得在Linux 下的c99模式还是什么里是可以的,记不得了,一般 的这样编译是通不过的!你可以用链表来做!

int n;

scanf("%d",&n);

int *a=(int *)malloc(4*n);

 

while(scanf(...)!=EOF) (输入到文件结束标志为止,ctrl+D) 另外的话你可以先输入一个数组下标n,然后再定义a[n];这样也可以

两种方法:

第一种:预定义一个足够大的数组例如int a[0xffff];

第二中:使用链表。

用malloc分配内存,

#include <stdio.h>

#include <malloc.h>

int main(){

    int lngAry;

    char * str;

    printf("Please input the long of the array:");

    scanf("%d",&lngAry);

    str=(char*)malloc(sizeof(char)*lngAry+1);

    /*

      这里分配了lngAry+1字节的内存,可以通过*(str+1)=... *(str+2)等使用

     */

    return 0;

}

上一个:vc编写C语言问题
下一个:c 语言怎么复习啊

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,