Reputation: 559
#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.
Upvotes: 0
Views: 82
Reputation: 145287
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;
}
Upvotes: 3
Reputation: 477514
strlen(str)
has undefined behaviour, because it is reading uninitialized values.
Upvotes: 2