开发者

Help writing getstring function

Im having some trouble writing a getstring function, this is what开发者_运维知识库 I have so far.

Regards, V

const char* getstring()
{


    char *buffer;
    int i = 255;

    buffer = (char *)malloc(i*sizeof(char));

    *buffer = getchar();
    while ( *buffer != '\n' )
    {
        buffer++;
        *buffer = getchar();
    }
    *buffer = '\0';

    const char* _temp = buffer;
    return _temp;
}


int main()
{
    char* temp = getstring();

    for ( ;temp++ ; *temp != '\0')
    {
        printf("%c", *temp);
    }

    return 0;
}


You're setting _temp to buffer when the latter points at the terminating '\0' of the string.

Move the line:

const char* _temp = buffer;

to be immediately after the line:

buffer = (char *)malloc(i*sizeof(char));

so that _temp is pointing to the start of the buffer.

You have some other problems:

  1. Don't use the name _temp - names with a leading underscore are reserved;

  2. You need to test that you don't write more than i bytes into the buffer;

  3. You should test for malloc() returning NULL;

  4. You need to test for getchar() returning EOF. This will mean you need to store the getchar() result in a variable of type int before you assign it to *buffer;

  5. As Michael Mrozek points out in a comment, the expressions in your for loop are the wrong way around.

...and as a point of style, sizeof(char) is always 1, so multiplying by it is unnecessary; and casting the result of malloc() is unnecessary in C and considered undesirable (unlike C++, where it is required).


Why not just use

char buffer[255];
scanf("%254s", &buffer);

or

char* buffer = readline("GO GO GO:");


const char* _temp = buffer;

Move the above statement just after the call to malloc

Important:
Free the memory allocated to buffer after its use in main().

free(temp);


You need to keep track of the allocated pointer - the value returned by malloc() - immediately after calling malloc() so you can pass it back to the caller. You should also check for EOF as well as newline - and that requires an int (not a char) to hold the value from getchar(). At minimum!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜