2017-01-05 9 views
0
int getstring(void) 
{ 
    char *x; 
    int i = 0; 
    x = malloc(sizeof(char) + 1); 
    char ch; 
    while ((ch = getchar()) != EOF) 
    { 
    x[i] = getchar(); 
    x = realloc(x, sizeof(char) + i + 1); 
    i++; 
    } 
    return *x; 
} 

この関数をメインで使用した後に文字列を入力する関数を作成しようとしていますが、出力が得られないようです。このコードでどこが間違っていましたか

+9

なぜあなたは 'int'を返すのですか?あなたの関数は 'char *'を返し、 'return * x;'は 'return x;'でなければなりません。 – mch

+2

また、文字列の0ターミネータも忘れています。 – mch

+0

前のコメントに加えて、「入力がない」とはどういう意味ですか?あなたの戻り値が期待どおりでないことを意味しますか? –

答えて

0

私はこのようにそれをやった:

#include <stdio.h> 
#include <stdlib.h> 
//----------------------------------- 
char* getstring(void) 
    { 
    char *x; 
    int i = 0; 
    x = malloc(sizeof(char)); 
    int ch; 
    while (((ch = getchar()) != EOF) && (i<99)) 
    { 
    x[i] = (char)ch; 
    i++; 
    x = realloc(x ,sizeof(char)*(i+1)); 
    } 
    x[i]=0; 
    return x; 
    } 
//----------------------------------- 
int main() 
    { 
    char *s; 
    s=getstring(); 
    printf("\nYou entered : %s\n",s); 
    free(s); 
    return 0; 
    } 
//----------------------------------- 

/* 

On Ubuntu linux you have to press ENTER and ctrl-d at the end of your keyboard input 

output: 

[email protected]:~/Desktop/getstr$ ./tst 
This is a test... 

You entered : This is a test... 



*/ 
関連する問題