帮忙写getstring函数
我在编写 getstring 函数时遇到了一些麻烦,这就是我到目前为止所遇到的。
问候, 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当
_temp
指向字符串的终止'\0'
时,您将_temp
设置为buffer
。将行:移动
到紧接行:之后,
以便
_temp
指向缓冲区的开头。您还有其他一些问题:
不要使用名称
_temp
- 带有前导下划线的名称被保留;您需要测试您向缓冲区写入的字节数不超过
i
个字节;您应该测试
malloc()
返回NULL
;您需要测试
getchar()
返回EOF
。这意味着您需要将getchar()
结果存储在int
类型的变量中,然后再将其分配给*buffer
;正如 Michael Mrozek 在评论中指出的那样,
for
循环中的表达式是错误的。...并且从风格上来说,sizeof(char) 始终为 1,因此无需乘以它;并且在 C 中强制转换
malloc()
的结果是不必要的,并且被认为是不可取的(与 C++ 不同,C++ 是必需的)。You're setting
_temp
tobuffer
when the latter points at the terminating'\0'
of the string.Move the line:
to be immediately after the line:
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 ofmalloc()
is unnecessary in C and considered undesirable (unlike C++, where it is required).为什么不直接使用
或
Why not just use
or
将上述语句移至
malloc
调用之后重要:
在
main()
使用后释放分配给buffer
的内存。Move the above statement just after the call to
malloc
Important:
Free the memory allocated to
buffer
after its use inmain()
.您需要在调用
malloc()
之后立即跟踪分配的指针 - 由malloc()
返回的值,以便您可以将其传递回调用者。您还应该检查 EOF 以及换行符 - 这需要一个int
(而不是char
)来保存getchar()
中的值。至少!You need to keep track of the allocated pointer - the value returned by
malloc()
- immediately after callingmalloc()
so you can pass it back to the caller. You should also check for EOF as well as newline - and that requires anint
(not achar
) to hold the value fromgetchar()
. At minimum!