[英]Simple C program. String returning from function causes Error
以下是Stephen Kochan编写的《用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.
这是为什么? 我如何使用那一行代替它工作? 另外,我对返回字符串/数组的函数有些困惑。 他们往往会导致我犯错误,因此,如果有人可以向我提供一些建议,那么在与他们合作时我应该始终牢记,这将对我有很大帮助。 先感谢您。
printf("From \"%s\" this part is being excluded-> \"%s\"\n", text1, subString( text1, 4, 3, result ) );
请注意, subString()
返回的字符不是char*
并且您正在使用%s
打印字符,这将导致未定义的行为。
您的数组在函数subString()
被修改,在第一种情况下,您通过返回result[count + 1]
打印数组结果,并且还存在未定义的行为
result[20] = subString( text1, 4, 3, result );
阵列越界访问
您需要像这样修改代码
char *subString (const char source[], int start, int count, char result[]){ //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;
}
int main()
{
// Keep your array here
char *p = subString( text1, 4, 3, result );
printf("%s\n",p);
}
要么
void subString (const char source[], int start, int count, char result[]){ //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';
}
在main()
printf("%s\n",result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.