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
_temptobufferwhen the latter points at the terminating'\0'of the string.Move the line:
to be immediately after the line:
so that
_tempis pointing to the start of the buffer.You have some other problems:
Don’t use the name
_temp– names with a leading underscore are reserved;You need to test that you don’t write more than
ibytes into the buffer;You should test for
malloc()returningNULL;You need to test for
getchar()returningEOF. This will mean you need to store thegetchar()result in a variable of typeintbefore you assign it to*buffer;As Michael Mrozek points out in a comment, the expressions in your
forloop 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 ofmalloc()is unnecessary in C and considered undesirable (unlike C++, where it is required).