Reputation: 834
I want to copy an array in C to another array, and then print them both out. When I print out the second array, it prints out twice. What is causing the duplicate?
When I debug (Xcode), everything seems normal until after the final iteration of the for loop, and suddenly, the test2 array equals "testtest".
#include <stdio.h>
int main()
{
char test1[4];
char test2[4];
test1[0] = 't';
test1[1] = 'e';
test1[2] = 's';
test1[3] = 't';
/* Copy the stuff from test1 into test2 */
for(int j = 0; j<4; j++){
test2[j] = test1[j];
}
printf("test1: %s\n", test1);
printf("test2: %s\n", test2);
printf("end testing");
return 0;
}
My results are:
test1: test
test2: testtest
end testing
Upvotes: 1
Views: 929
Reputation: 47
Try using the String copy function
int main(){
char test1[4];
char test2[4];
test1[0] = 't';
test1[1] = 'e';
test1[2] = 's';
test1[3] = 't';
strcpy(test2, test1);
printf("test1: %s\n", test1);
printf("test2: %s\n", test2);
printf("end testing");
return 0;
}
Upvotes: 0
Reputation: 30926
Your code has undefined behavior. The char
array is not null terminated.
Twice ouputted because it didn't get the \0
and then it outputted adjacent variables value test1
and test2
.
%s
expects a null terminated char array or string. You didn't provide it. And it seems that char
array test1
and test2
are adjacent in memory. As it didn't know where to stop because it didn't get any \0
- it printed two arrays content. Then it somehow got \0
and it stopped. But in case there was not any \0
adjacent to the memory it will go on printing. You can't or should reply on this behavior.
You can do this by the way but again you would better use nul terminated char array. (Makes life easier).
printf("%.*s",4,test1);
printf("%.*s",4,test2);
You can initialize the string like this
char test1[]="test";
Then you can use strcpy
to copy the string - though make sure you have destination with appropriate size (taking into account the nul terminating character also).
Don't use gets()
- instead use fgets()
or similar function.
Upvotes: 2
Reputation: 197
C strings are null terminated. If you don't put a null character ('\0') at the end of the string, it actually is not going to work properly (because of the mistake). Do this:
char test1[5]; //****
char test2[5];
test1[0] = 't';
test1[1] = 'e';
test1[2] = 's';
test1[3] = 't';
test1[4] = '\0'; //****
/* Copy the stuff from test1 into test2 */
for(int j = 0; j<4; j++){
test2[j] = test1[j];
}
test2[j] = '\0'; //****
But you don't need to put a '\0' when you take the entire string input from the user like: scanf("%s", s)
or gets(s)
, because it's put then automatically.
Upvotes: 1