I'm new to C++, and I'm having trouble to concatenate a const char* with a char aray.
First, I'd like to ask a question: Is const char* the same as std::string?
And going straight to my problem, this is what I'm trying:
I have this 10 sized char array that contains letters from a to j:
char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', j};
And I want to store this array (or part of it), using a const char*. But I could not do the concatenation, I thought it would be some think like this:
const char* group_of_letters = "\0";
for(int i = 0; i <= 9; i++){
group_of_letters += my_array[i];
}
I'd like to use the for loop because I'll need it on my real project to store defined intervals of that array into the const char* But it didn't work any way that I have tried.
If it helps, my complete code would look like this:
#include <iostream>
int main(){
char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
const char* group_of_letters = "\0";
for(int i = 0; i <= 9; i++){
group_of_letters += my_array[i];
}
std::cout << group_of_letters;
return 0;
}
->Using Dev C++ 5.11 - 06/08/2023
std::stringis far different from a constant string literal. It is the case thatstd::stringinternally uses its ownallocatorto allocate needed memory space to construct a string from its constructor argument. You can access a C-style pointer tostd::string's buffer viac_strfunction.const char*, in fact must be interpreted as a pointer to constant char and not a constant pointer to char, because you would be able to increment and decrement the pointer, which shows the fact that it is being a pointer to a non-modifiable block of memory. What you make when you write something likeis that in memory, there is a block where all characters of "This is a test" laid down there sequentially and indeed this block is in
.rodata sectionorread-only sectionof the final object file.You define a pointer named
strto point to this block of memory, and you can modify the pointer itself by something likestr++orstr--but cannot modify its content. Therefore something like*(str) = 'k'would give you aSegmentation Faulterror.std::stringis a C++ class which encapsulates the string you made and gives access to many different class methods where you are able to get informed about different properties and values of the string. As mentioned, you can access the C-styleconst char*buffer byc_str, access the size of string bysize, and many more. Just look here for more information.Back to your question, I would recommend considering something like the following: