c string difficulty

1
2
3
4
char literal [] = "Anna Bannana";
char destination[5];
strcpy(destination, literal);
cout<<destination<<endl;


I would expect a truncated result to = 5 characters. Instead it prints the entire source string:

Anna Bannana

2nd probably related problem:
1
2
3
4
5
cout<<"Try getline again :";
char string[10];
cin>>string;
cin.getline(string, 10);
cout << string << endl;


No output
strcpy doesn't know about the length of the destination array so it will overwrite whatever is stored after the array in memory. This could lead to the program crashing or in other ways not functioning correctly.

In your second program cin>> will read the first word and cin.getline will read the rest of the line. Note that getline overwrites the content of the string so the first word you input will be lost. If you input "Anna Bannana" only " Bannana" will be outputted. If you input only "Anna" then nothing will be outputted.
Thx for the reply.

Got most of it except:

strcpy doesn't know about the length of the destination array


char destination[5];

Destination is initialized with a fixed array size.
It's not possible for strcpy to know the size of the array because what is being passed to the function is in fact a pointer to the first char in the array. strcpy just assumes the array is big enough.

You have the same problem with cin>> and cin.getline in your second program. If you enter a word that is longer than 9 characters you are in trouble. That's why it's much safer to use std::string. If you use C strings you need to be very careful.
Which means that the source string can only contain 4 characters.

You probably should be using strncpy() instead of strcpy() but be sure that the string is properly terminated.

Topic archived. No new replies allowed.