c语言如何输入任意长度的字符串数组

比如说我在linux里打这样的command
printf '\0Gur\n\0Dhvpx\n\0Oebja\n\0sbk\n\twhzcf\n\tbire\n\tgur\n\tynml\n\tqbt.' |
./sort
它能把\0Gur,\0Dhvpx,\0Oebja。。。都输入到char **word里,以\n区分不同字符串,但是能够包括\0,而且数组的长度是任意的
貌似有点难度,求大神帮助

“任意长度”实际上是做不到的,即使所用的软件平台没有限制,硬件环境也不允许。所以“任意长度”应当理解为在一个很大的空间之内没有限制地输入字符串而不用事先确定长度。鉴于这种理解,可以定义一个输入函数,先动态申请一个较大的空间,直接向其内输入字符串;输入完毕后检测其长度,再按实际需要申请一个合适大小的空间,把刚才输入的字符串拷贝到这个合适大小的空间里,再把原先申请的大空间释放。举例代码如下:

//#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个回答  2013-02-10
以下是我的思路,仅供楼主参考:
遍历数组,统计'\n'的次数,从而为指向字符串的指针数组分配内存。
然后遍历数组,计算当前子字符串的字符数,然后分配内存,copy。
第2个回答  2013-02-10
你想:
(1)\0\n\t 这些属 转义字符,你现在想 作为 非转义字符 输入和判断。
(2)以\n区分不同字符串,但输入串最后 有 \n 还是没有,还是可能有可能无?
(3)输入长度不定,结果存入 **word.
解决办法:
用gets() 读入整行输入
分析有多少个 \n 和 字符串最长的长度需要。
动态分配 word.
把整行 字符串 ,拆开 存入 word
程序如下:
#include<stdio.h>
main(){
char c;
char buff[4098];
int L,i,j,n=0,w=0,wm=0,N;
char **word;
gets(buff);
L = strlen(buff);for (i=0;i<L-1;i++)
{
if (buff[i+1]=='n' && buff[i]=='\\'){
if (w>wm) {wm=w;};
n++;i++;w=0;
}
w++;
}
printf("n=%d wm=%d\n",n,wm);

N=n+1;
word = (char **) malloc(sizeof(char *) * N);for (i = 0; i < N; i++)
word[i] = (char *) malloc(sizeof(char) * wm);

L = strlen(buff); n=0;w=0;for (i=0;i<L-1;i++)
{
word[n][w]=buff[i];
if (buff[i+1]=='n' && buff[i]=='\\'){
word[n][w]='\0';
n++;i++;w=0;
}
w++;
}

for (j=0;j<N-1;j++){for (i=0;i<wm;i++) printf("%c",word[j][i]);
printf("\n");
}
printf("%s\n",word[j]);

return 0; }

例子:
\0Gur\n\0Dhvpx\n\0Oebja\n\0sbk\n\twhzcf\n\tbire\n\tgur\n\tynml\n\tqbt\n
n=9 wm=8
\0Gur
\0Dhvpx
\0Oebja
\0sbk
\twhzcf
\tbire
\tgur
\tynml
\tqbt本回答被提问者采纳
第3个回答  2013-02-10
任意的?有多长呢?

define len 长度
char **word【len】

if(word【len】==“、n”)

唉。。
第4个回答  2013-02-10
干嘛不做环境变量呢 ?
相似回答