【发布时间】:2015-06-21 07:51:54
【问题描述】:
以下是 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.
这是为什么呢?我怎样才能使用那一行来代替它呢? 另外,我对返回字符串/数组的函数有点困惑。他们往往会导致我犯错误,所以如果有人能给我一些建议,我在与他们合作时应该始终牢记在心,这对我很有帮助。提前谢谢你。
【问题讨论】:
-
没有名为
result[20]的有效元素。提示:0基于索引。 -
您可能需要检查参数并确保 start+count 不会超出源字符串的范围。并且循环应该被去混淆成这样:
for(i = 0; i<count; i++) result[i] = source[i+start]; -
@Sourav Ghosh 我用内存中的 20 个位置初始化了字符串并在其中放入了一个 null,因为不久前有人告诉我,当我初始化它们时,我应该总是在其中填充 null 终止符(无论大小),因为这是一种很好的编程习惯。
-
@Lundin 是的,你是对的,这会让事情变得更容易。
-
@RestlessC0bra 请看我的回答。我正在考虑不存在的第 21 个元素。 :-)
标签: c string function pointers return