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:
Don't use the name
_temp
- names with a leading underscore are reserved;You need to test that you don't write more than
i
bytes 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 typeint
before you assign it to*buffer
;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!
精彩评论