tags:

views:

50

answers:

4

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;
}
+2  A: 

If this is homework, you should add the homework tag. Otherwise, why not just use

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

or

char* buffer = readline("GO GO GO:");
Michael Mrozek
Or: fgets(buffer, sizeof(buffer), stdin);
Jonathan Leffler
No this isn't homework. I suppose I could of mentioned that the function is to get strings from serial on an ARM MCU but I didn't think it was relevant.I dont think any of them options will work, Thanks
volting
A: 

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!

Jonathan Leffler
+2  A: 

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).

caf
Minor sidenote not worthy of its own answer: the for loop arguments are backwards
Michael Mrozek
Yes made all of the changes and its working fine now.Not sure even how the for loop got so contorted, It must of got worped at some point when I was experimenting.Thanks,V
volting
+1  A: 
N 1.1
Yes forgot to do that,Thanks,V
volting