简体   繁体   中英

copy a c string into a char array

New to C, still getting a grasp on pointers. I'm trying to add a copy of ac string into a 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 to make a copy because temp is constantly being replaced with new characters and a pointer to temp obviously won't suffice as i want to do this after abc is 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'. PS this is what i have so far, but it doesn't work. I'm not too sure if im using strcpy incorrectly, but any alternatives would be helpful.

You are using strcpy correctly, but you are not giving it proper memory. That is why both your programs have undefined behavior - they write to memory pointed by uninitialized pointers.

To fix this, allocate memory to 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 to add 1 to the result of strlen in order to accommodate the null terminator of your C string. Note that the cast of malloc is necessary only because you are using C++; in C, the cast in front of malloc can be dropped.

Note: I assume that this is a learning exercise to learn ways to work with "raw" pointers, because C++ provides much better facilities for working with strings. In particular, your container could be replaced with a std::vector<std::string> which would grow dynamically as you add items to it, and manage its own memory, thus eliminating the need to use malloc and strcpy .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM