[英]why this function returns null?
This code finds the next word in the string. 此代码查找字符串中的下一个单词。
For example 例如
given an input of " my cake"
the function should return "my cake"
. 给定
" my cake"
的输入,该函数应返回"my cake"
。 as the expected output 作为预期的输出
If I use return
then the output is (null), but I use printf
then the code works 如果我使用
return
则输出为(null),但是我使用printf
则代码有效
I would like to know how to get the expected output using return. 我想知道如何使用return获得预期的输出。
#include <stdio.h>
int main()
{
char* str[1000];
printf("enter:");
fgets(str,1000,stdin);
printf("%s",find_word_start(str));
}
char* find_word_start(char* str){
char* result[1000];
int c = 0, d = 0;
while(str[c] ==' ') {
c++;
}
while(str[c] != '\0'){
result[d++] = str[c++];
if(str[c]==' ') {
result[d++] = str[c++];
}
while(str[c]==' ') { //
c++;
}
}
result[d] = '\0';
//print or return char?
return result;
}
char* result[1000];
creates an array of 1000 pointers. 创建一个包含1000个指针的数组。 That's wrong in a number of ways.
这在很多方面都是错误的。
malloc
(or something that does a malloc
such as strdup
). malloc
(或执行malloc
例如strdup
)。 Fix: 固定:
// Returns a copy that needs to be freed.
char* find_word_start(const char* src) {
while (*src == ' ')
++src;
size_t len = 0;
while (str[len] != '\0')
++len;
++len; // Include NUL
result = malloc(len);
char* dst = result;
while (len--)
*(dst++) = *(src++);
return result;
}
Well, I was avoiding using string functions above like you did, but they greatly simplify the solution. 好吧,我避免像您一样使用上面的字符串函数,但是它们大大简化了解决方案。
// Returns a copy that needs to be freed.
char* find_word_start(const char* src) {
while (*src == ' ')
++src;
return strdup(src);
}
That said, since you return the tail end of the string, you could simply return a pointer into the existing string. 就是说,由于您返回了字符串的尾部,因此可以简单地将指针返回到现有字符串中。
// Returns a pointer into the provided string.
const char* find_word_start(const char* str) {
while (*str == ' ')
++str;
return str;
}
The following line allocates memory space in the stack but after the function ends everything is gone: 以下行在堆栈中分配内存空间,但是在函数结束后,所有内容都消失了:
char result[1000];
You need to allocate memory in the heap like that: 您需要像这样在堆中分配内存:
char *result = malloc(sizeof(char) *1000);
Note: don't forget to free that memory space by free
function. 注意:不要忘记通过
free
功能释放该内存空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.