c++ - copy a c string into a char array -


new c, still getting grasp on pointers. i'm trying add copy of c string char array such that

char temp[40]; temp[0] = 'a'; temp[1] = 'b'; temp[2] = 'c'; temp[3] = null; char *container[40] = {0}; strcpy(container[0], temp); cout << container[0] << endl; 

prints "abc". trying make copy because temp being replaced new characters , pointer temp won't suffice want after abc printed.

char temp[40]; temp[0] = 'd'; temp[1] = 'e'; temp[2] = 'f'; temp[3] = null; char *container[40] = {0}; strcpy(container[1], temp); cout << container[1] << endl; 

prints 'def'. p.s have far, doesn't work. i'm not sure if im using strcpy incorrectly, alternatives helpful.

you using strcpy correctly, not giving proper memory. why both programs have undefined behavior - write memory pointed uninitialized pointers.

to fix this, allocate memory each element of container using malloc:

char temp[40]; temp[0] = 'a'; temp[1] = 'b'; temp[2] = 'c'; temp[3] = null; char *container[40] = {0}; container[0] = (char*)malloc(strlen(temp)+1); strcpy(container[0], temp); cout << container[0] << endl; 

you need add 1 result of strlen in order accommodate null terminator of c string. note cast of malloc necessary because using c++; in c, cast in front of malloc can dropped.

note: assume learning exercise learn ways work "raw" pointers, because c++ provides better facilities working strings. in particular, container replaced std::vector<std::string> grow dynamically add items it, , manage own memory, eliminating need use malloc , strcpy.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -