#include <stdio.h>
#include <string.h>
main() {
int i = 0, j = 0;
char ch[] = { "chicken is good" };
char str[100];
while ((str[i++] = ch[j++]) != '\0') {
if (i == strlen(str))
break;
}
printf("%s", str);
}
I want to copy the string "chicken is good"
from ch
to str
using a while
loop. But when I print str
the output shows "chi"
. It only prints part of the string. Is my condition wrong?
I am using Dev c++ as my IDE and the version of my compiler is gcc 4.9.2. And also I am new to programming.
The statement if (i == strlen(str)) break;
is useless and has undefined behavior since str
is not yet null terminated.
Note that your program has other problems:
main
function as int
. You are using an obsolete syntax. i
and j
for the source and destination arrays. They always have the same value. 0
at the end of main()
. Here is a simpler version:
#include <stdio.h>
int main(void) {
int i;
char ch[] = "chicken is good";
char str[100];
for (i = 0; (str[i] = ch[i]) != '\0'; i++) {
continue;
}
printf("%s\n", str);
return 0;
}
strlen(str)
具有未定义的行为,因为它正在读取未初始化的值。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.