以下是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.
为什么?我怎样才能使用那一行代替它呢? 另外,我对返回字符串/数组的函数有点困惑。他们倾向于引导我犯错误,所以如果有人能给我提出一些建议,那么在与他们合作时我应该始终牢记这一点,这对我非常有帮助。提前谢谢。
答案 0 :(得分:2)
第1点:
在第一种情况下,您使用的result
值通过作为参数传递给subString()
而被修改。你没有使用subString ()
fucntion的返回值。
OTOH,在第二种方法中,你试图使用subString ()
函数的重新转换值,这也是使用错误的格式说明符。您可以在man page of printf()
第2点
C
中的数组索引从0
开始。因此,没有名为result[20]
的有效元素。因此,
result[20] = subString( text1, 4, 3, result );
导致一个错误,然后调用undefined behaviour。
答案 1 :(得分:1)
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);