“任意长度”实际上是做不到的,即使所用的软件平台没有限制,硬件环境也不允许。所以“任意长度”应当理解为在一个很大的空间之内没有限制地输入字符串而不用事先确定长度。鉴于这种理解,可以定义一个输入函数,先动态申请一个较大的空间,直接向其内输入字符串;输入完毕后检测其长度,再按实际需要申请一个合适大小的空间,把刚才输入的字符串拷贝到这个合适大小的空间里,再把原先申请的大空间释放。举例代码如下:
//#include "stdafx.h"//If the vc++6.0, with this line.#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#define N 131071
char *Any_Long_Str(char *p){
char *pt
if((pt=(char *)malloc(N))==NULL){//Apply for a larger space for temporary use
printf("Apply for temporary use of space to fail...\n")
exit(0)
}
gets(pt)//Get a string from the keyboard
if((p=(char *)malloc(strlen(pt)+1))==NULL){//Apply for a suitable size of space
printf("Application memory failure...\n")
exit(0)
}
strcpy(p,pt)//Copy the string pt to p
free(pt)//Release the temporary use of space
return p
}
int main(void){
char *pstr=NULL
printf("Input a string:\n")
pstr=Any_Long_Str(pstr)
printf("%s\n",pstr)//Look at...
free(pstr)//Release the space
return 0
}
1、输入数组需要使用指针获取地址后,就能对得到的数组就行操作了。首先打开DEV C++软件,新建一个空白的C语言文件:
2、输入程序的源码,先定义一个整型数组“a[5]”,采用scanf语句输入数组中的每个元素,这里使用指针来对输入的数字进行访问,要先给输入的每一个数字给予它的地址,便于访问,最后拿得到的数计算出平均值输出,程序就编写完成了:
3、代码全部编写成功之后编译运行,在弹出的输入面板中输入任意5个整数,按回车键,即可得出平均值,以上就是用C语言输入一个数组,关键点是数组的获取要用指针:
动态分配的数组可以自定义数组的长度,示例如下:#include <stdio.h>#include <string.h>#include <stdlib.h>int main(){printf("输入要分配的内存大小:")int sizescanf("%d", &size) //输入自定义的数组长度int *pstart = (int *)malloc(sizeof(int) *size)if (pstart==0) {printf("不能分配内存\n")return 0}memset(pstart, 0x00, sizeof(int) * size)int inxfor (inx=0inx!=size++inx) pstart[inx] = inxfor (inx=0inx!=size++inx) printf("%d\t", pstart[inx])printf("\n")return 0}