为什么我的子字符串没有保存在ST1'在for循环中,但是当我试图在循环中打印每个st1的每个值时,它正在工作?
为什么在循环的中,
st1
的值未保存:当我打印st1
时,什么都没打印?
#include <stdio.h>
#include <stdlib.h>
int main() {
char s[40] = "Who are you to tell me that I can not code?";
char st1[15];
for (int i = 2; i < 9; i++) {
st1[i] = s[i];
printf("%c", s[i]);
}
printf("\n Now Printing the Whole at once \n");
printf("%s", st1);
return 0;
}
这是输出.....
o are y
Now Printing the Whole at once
Process returned 0 (0x0) execution time : 0.052 s
Press any key to continue.
Why in the for
loop the value of st1
is not saved ie: when I'm printing st1
nothing is being printed?
#include <stdio.h>
#include <stdlib.h>
int main() {
char s[40] = "Who are you to tell me that I can not code?";
char st1[15];
for (int i = 2; i < 9; i++) {
st1[i] = s[i];
printf("%c", s[i]);
}
printf("\n Now Printing the Whole at once \n");
printf("%s", st1);
return 0;
}
Here is the Output.....
o are y
Now Printing the Whole at once
Process returned 0 (0x0) execution time : 0.052 s
Press any key to continue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的代码
st [0]
和st [1]
中,从未设置,因此使用printf
打印字符串的行为不确定。st [0]
可能恰好是一个空字节,因此printf
什么也没打印。您应该在
st1
中使用其他索引,并在末尾设置一个空字节。还要注意,
s
也不是终止终止的,因为它具有40个字符,因此无空间用于NULL终结器字节。这是一个修改版本:
In your code
st[0]
andst[1]
are never set, so printing the string withprintf
has undefined behavior.st[0]
probably happens to be a null byte, soprintf
prints nothing.You should use a different index into
st1
and set a null byte at the end.Beware also that
s
is not null terminated either because it has exactly 40 characters so no space for a null terminator byte.Here is a modified version:
此循环
从索引[2,8]处读取
s
,但也将索引[2,8]的st1
写入。这意味着st1
的索引[0,1]和[9,14]包含不确定值,从未初始化。读取这些值是不确定的行为。使用单独的索引从
st1
的开头放置值,并确保 null-entration 结果。除了:该初始化器(类型
char [44]
)对于初始化的数组来说太长了。使用空尺寸声明器将数组自动尺寸自动尺寸以匹配其初始化器。
This loop
reads from
s
at indices [2, 8], but also writes tost1
at indices [2, 8]. This means indices [0, 1] and [9, 14] ofst1
contain indeterminate values, having never been initialized. Reading these values is a form of undefined behaviour.Use a separate index to place values from the start of
st1
, and make sure to null-terminate the result.Aside: this initializer, being of type
char [44]
, is too long for the array being initialized.Use an empty size declarator to have the array automatically sized to match its initializer.