【发布时间】:2014-09-22 20:44:13
【问题描述】:
据推测,这段代码中有一个错误,但它运行良好并且输出符合我的预期(“hello world”)。 return str有问题吗?
#include <string.h>
char* example(){
// your code goes here
char str[12];
strncpy(str, "hello world", 11);
str[11] = 0;
printf("%s\n",str);
return str;
}
int main() {
char * check = example();
return 0;
}
输出:
Success time: 0 memory: 2248 signal:0
hello world
【问题讨论】:
-
您在寻找
null byte '\0'吗?在任何情况下,您都不必使用 strncpy 手动设置空字节。 -
strncpy 你做@C.B.它会在处理 n 个字符时停止,并且可能不会设置空终止符。在这种情况下,它肯定不会。
-
@KeithNicholas 仅当源长度超过要复制的 num 个字节时,对吧?
-
@C.B,对,就像他一样。 11 是字符数,所以他错过了复制 0
-
@KeithNicholas 对,我的错