以下是 Stephen Kochan 所著的《Programming in C》一书的练习 10.4。它说我应该创建一个函数,从输入字符串派生一部分并将该部分返回到 main() (作为字符串,而不是指针)并显示它。 我的代码如下。
#include <stdio.h>
char subString (const char source[], int start, int count, char result[count + 1] ){ //result will be number of characters (count) + 1 (because of null)
int i, j, end = start + count;
// the part excluded must start from i = start and "count" number of characters must be derived and then put on result
for( i = start, j = 0; i < end; ++i, ++j)
result[j] = source[i];
result[j] = '\0';
return result[count + 1];
}
int main (void){
char result[20] = {0};
const char text1[] = "character";
result[20] = subString( text1, 4, 3, result );
printf("From \"%s\" this part is being excluded-> \"%s\"\n", text1, result);
return 0;
}
输出是
From "character" this part is being excluded-> "act"
Process returned 0 (0x0) execution time : 0.332 s
Press any key to continue.
请注意,上面的代码运行得很好 - 没有警告。
我无法理解的是当我替换下面的两行时
result[20] = subString( text1, 4, 3, result );
printf("From \"%s\" this part is being excluded-> \"%s\"\n", text1, result);
用这一行
printf("From \"%s\" this part is being excluded-> \"%s\"\n", text1, subString( text1, 4, 3, result ) );
我得到输出:
From "character" this part is being excluded-> "(null)"
Process returned 0 (0x0) execution time : 0.332 s
Press any key to continue.
这是为什么呢?我怎样才能用那一行来让它工作呢? 另外,我对返回字符串/数组的函数有点困惑。他们往往会引导我犯错误,所以如果有人能给我提供一些建议,我在与他们合作时应该始终牢记这些建议,这将对我很有帮助。预先感谢您。
最佳答案
第 1 点:
在第一种情况下,您使用的是通过作为参数传递给 subString()
进行修改的 result
值。您没有使用subString ()
函数的返回值。
OTOH,在第二种方法中,您尝试使用 subString ()
函数的返回值,这也使用了错误的格式说明符。您可以在 man page of printf()
中了解有关正确格式说明符的更多信息。
第2点
C
中的数组索引从 0
开始。因此,不存在名为 result[20]
的有效元素。因此,
result[20] = subString( text1, 4, 3, result );
导致差一错误,进而调用undefined behaviour .
关于c - 简单的C程序。从函数返回的字符串导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29648766/