C++, conversion from string to char array - c++

I would like to perform the above mentioned operation, however I would like to make sure that the char array is exactly the same size with the string at hand.
So the real question is, how can I make an array with a size that is going to be determined in the run time?

allocating memory on the free store, and copying the string in one go:
std::string s("abcdef");
...
char* chars=strdup(s.c_str());
You need to free the memory manually, of course. Documentation e.g. on the man page. As #Loki mentions: freeing this memory is done through free(chars), not through delete. Also, you need to include the <cstring> header.
If you want to stay in the c++ world, use a vector; it can be created with two iterators to copy it's data from, and will allocate on the heap, and will cleanup by itself. Isn't that a treat?
std::vector<char> vec( s.begin(), s.end() );

You can create an array of size known at runtime with the "new" operator:
char* res = new char[str.size()+1];
strncpy(res, str.c_str(), str.size()+1);

std::string s = "hello";
char* c = new char[s.length() + 1]; // '+ 1' is for trailing NULL character.
strcpy(c, s.c_str());

#include <string>
int main(int argc, char *argv[])
{
std::string random_data("This is a string");
char *array=new char[random_data.size()+1];
// do stuff
delete[] array;
return 0;
}

Try:
char* res = new char[str.size()+1](); // Note the () makes sure it is '0' filled.
std::copy(str.begin(), str.end(), res); // Don't need to copy the '\0' as underlying
// array already has '\0' at the end position.
...
delete [] res; // Must not forget to delete.
Or: (preferably)
std::vector<char> res(str.begin(), str.end());
Or: If all you want to do is call a C-unction:
str.c_str()

Use strlen() to find the length of the string, then malloc() a char array of that size.

Related

Do not understand about strcpy in C++

char* s1;
strcpy(s1,"smilehihi");
s1[6] = 'a';
When I compile, VS do not have any errors. But in the runtime, my code makes mistake. I think I do not really understand about strcpy
The main issue here is not the strcpy() function but the fact that you don't allocate any memory for the string itself.
If I were you, I would do something like
char* s1=(char*)malloc(SIZE); // the SIZE is the predefined maximum size of your string
strcpy(s1,"smilehihi");
s1[6] = 'a';
Edit:
Just as an advice, consider using stpncpy(). It helps to avoid buffer overflow, and, in your case, will help you avoid exceeding the maximum size of char*
char * stpncpy(char * dst, const char * src, size_t len);
The problem is that you have not allocated any space for what you wish to store in s1: "smilehihi". You declare s1 as a pointer variable, but it needs something to point at. You can allocate space by using the new operator.
char* s1 = new char[stringLength + 1]; //stringLength = length of string stored
// + 1 to hold null terminator character
strcpy(s1, "smilehihi");
s1[6] = 'a';
You have to declare #define _CRT_SECURE_NO_WARNINGS at the top of your main file to avoid an error during compilation due to strcpy() being deprecated.
You need to allocate variable first by malloc() or by using the keyword new .
Also deallocate the memory at the end
At first you should allocate char* s1.
char *s1 = new char[9]; // C++ version
or you can you use C version:
char *s1 = (char*)malloc(9);
Then you can use following code:
strcpy(s1, "smilehihi");
s1[6] = 'a';

Filling char pointer correctly

I have a char pointer:
char* s = new char[150];
Now how do i fill it? This:
s="abcdef";
Gives warning about deprecation of conversion between string literal and char*, but generally works.
This:
char* s = new[150]("abcdef");
Does not work, gives an error.
How to do this properly? Note that I want the memory allocation to have 150*sizeof(char) bytes and contain "abcdef". I know about malloc, but is it possible to do with new?
Its for an assignment where i cant use the standard library.
This sequence of statements
char* s = new char[150];
s="abcdef";
results in a memory leak because at first a memory was allocated and its address was assigned to the pointer s and then the pointer was reassigned with the address of the string literal "abcdef". And moreover string literals in C++ (opposite to C) have types of constant character arrays.
If you allocated a memory for a string then you should copy a string in the memory either by using the C standard function strcpy or C standard function strncpy.
For example
char* s = new char[150];
std::strcpy( s, "abcdef" );
Or
const size_t N = 150;
char* s = new char[N];
std::strncpy( s, "abcdef", N );
s[N-1] = '\0';
Or even the following way
#include <iostream>
#include <cstring>
int main()
{
const size_t N = 150;
char *s = new char[N]{ '\0' };
std::strncpy( s, "abcdef", N - 1 );
std::cout << s << '\n';
delete []s;
}
In any case it is better just to use the standard class std::string.
std::string s( "abcdef" );
or for example
std::string s;
s.assign( "abcdef" );
The basic procedure for creating a memory area for a string and then filling it without using the Standard Library in C++ is as follows:
create the appropriate sized memory area with new
use a loop to copy characters from a string into the new area
So the source code would look like:
// function to copy a zero terminated char string to a new char string.
// loop requires a zero terminated char string as the source.
char *strcpyX (char *dest, const char *source)
{
char *destSave = dest; // save copy of the destination address to return
while (*dest++ = *source++); // copy characters up to and including zero terminator.
return destSave; // return destination pointer per standard library strcpy()
}
// somewhere in your code
char *s1 = new char [150];
strcpyX (s1, "abcdef");
Given a character array:
char * s = new char [256];
Here's how to fill the pointer:
std::fill(&s, &s + sizeof(s), 0);
Here's how to fill the array:
std::fill(s, s+256, '\0');
Here's how to assign or copy text into the array:
std::strcpy(s, "Hello");
You could also use std::copy:
static const char text[] = "World";
std::copy(text, text + sizeof(text), s);
Remember that a pointer, array and C-Style string are different concepts and objects.
Edit 1: Prefer std::string
In C++, prefer to use std::string for text rather than character arrays.
std::string s;
s = "abcdef";
std::cout << s << "\n";
Once you've allocated the memory for this string, you could use strcpy to populate it:
strcpy(s, "abcdef");

Copy vector<char> into char*

I'm just studying C and C++ programming.
I've searched and can't seem to find an answer that has a decent response. Of course using <string> is much easier but for this task I am REQUIRED to use only clib <string.h> functions; I'm also not allowed to use C++11 functions.
I have the 2 variables below, and want to move the contents of buffer into c.
vector<char> buffer;
char* c = "";
How can I do this easily?
I have this so far but it obviously doesn't work, otherwise I wouldn't be here.
for (int b = 0; b < buffer.size(); b++)
{
c += &buffer[b];
}
The simplest way I can think of is;
std::vector<char> buffer;
// some code that places data into buffer
char *c = new char[buffer.size()];
std::copy(buffer.begin(), buffer.end(), c);
// use c
delete [] c;
std::copy() is available in the standard header <algorithm>.
This assumes the code that places data into buffer explicitly takes care of inserting any trailing characters with value zero ('\0') into the buffer. Without that, subsequent usage of c cannot assume the presence of the '\0' terminator.
If you want to ensure a trailing '\0' is present in c even if buffer does not contain one, then one approach is;
std::vector<char> buffer;
// some code that places data into buffer
char *c = new char[buffer.size() + 1]; // additional room for a trailing '\0'
std::copy(buffer.begin(), buffer.end(), c);
c[buffer.size()] = '\0';
// use c
delete [] c;
One could also be sneaky and use another vector;
std::vector<char> container;
// some code that places data into buffer
std::vector<char> v(container); // v is a copy of container
v.push_back('\0'); // if we need to ensure a trailing '\0'
char *c = &v[0]
// use c like a normal array of char
As long as the code that uses c does not do anything that will resize v, the usage of c in this case is exactly equivalent to the preceding examples. This has an advantage that v will be released when it passes out of scope (no need to remember to delete anything) but a potential disadvantage that c cannot be used after that point (since it will be a dangling pointer).
First, allocate space for the data by assigning c = new char[buffer.size()];
Then use memcpy to copy the data: memcpy(c, buffer.data(), buffer.size())
Your for loop would work in place of memcpy, too.
Also note that if vector<char> stays in place all the time when you use char*, and you are allowed to change the content of the vector, you could simply use the data behind the vector with a simple assignment, like this:
char *c = buffer.data();
I'm noticing some weird behavior when I create my char* of the given size is that it creates it bigger with some random "hereýýýý««««««««" values after my word
It looks like you do need a null-terminated C string after all. In this case you need to allocate one extra character at the end, and set it to zero:
char *c = new char[buffer.size()+1];
memcpy(c, buffer.data(), buffer.size());
c[buffer.size()] = 0;
You can do it in this way:
vector<char> buffer;
//I am assuming that buffer has some data
char *c = new char[buffer.size()+1];
for( int i=0; i<buffer.size(); i++ )
c[i] = buffer[i];
c[i] = '\0';
buffer.clear();

How can I transfer string to char* (not const char*)

I wanna do something like:
string result;
char* a[100];
a[0]=result;
it seems that result.c_str() has to be const char*. Is there any way to do this?
You can take the address of the first character in the string.
a[0] = &result[0];
This is guaranteed to work in C++11. (The internal string representation must be contiguous and null-terminated like a C-style string)
In C++03 these guarantees do not exist, but all common implementations will work.
string result;
char a[100] = {0};
strncpy(a, result.c_str(), sizeof(a) - 1);
There is a member function (method) called "copy" to have this done.
but you need create the buffer first.
like this
string result;
char* a[100];
a[0] = new char[result.length() + 1];
result.copy(a[0], result.length(), 0);
a[0][result.length()] = '\0';
(references: http://www.cplusplus.com/reference/string/basic_string/copy/ )
by the way, I wonder if you means
string result;
char a[100];
You can do:
char a[100];
::strncpy(a, result.c_str(), 100);
Be careful of null termination.
The old fashioned way:
#include <string.h>
a[0] = strdup(result.c_str()); // allocates memory for a new string and copies it over
[...]
free(a[0]); // don't forget this or you leak memory!
If you really, truly can't avoid doing this, you shouldn't throw away all that C++ offers, and descend to using raw arrays and horrible functions like strncpy.
One reasonable possibility would be to copy the data from the string to a vector:
char const *temp = result.c_str();
std::vector<char> a(temp, temp+result.size()+1);
You can usually leave the data in the string though -- if you need a non-const pointer to the string's data, you can use &result[0].

How to delete char * in c++?

In my application, I create a char* like this:
class sample
{
public:
char *thread;
};
sample::sample()
{
thread = new char[10];
}
sample::~sample()
{
delete []thread;
}
Am I doing the right thing in the code?
If you have [] after your new, you need [] after your delete. Your code looks correct.
List of points to be noted:
1) You need to allocate room for n characters, where n is the number of characters in the string, plus the room for the trailing null byte.
2) You then changed the thread to point to a different string. So you have to use delete[] function for the variable you are created using new[].
But why are you fooling around with new and delete for character data? Why not just use std::string, instead of 'C' functions? It's amazing why so many don't do the easiest thing:
#include <cstdio>
#include <string>
int countWords(const char *p);
int main(int argc, char *argv[])
{
std::string pString = "The Quick Brown Fox!";
int numWords1 = countWords(pString.c_str());
printf("\n\n%d words are in the string %s", numWords1, pString.c_str());
int numWords2 = countWords(argv[1]);
printf("\n%d words are in the string %s", numWords2, argv[1]);
}
No need for new[], delete[], strcpy(), etc.
Use strlen(). Better yet, don't use char* and use std::string for string data.
It's "right"*, but it's very wrong.
You should not use new[], but instead use std::vector<char> or std::string. Even if you weren't doing that, you need to respect the rule of three, or your class is broken.
*Assuming you meant new char[10]. Also, more orthodox is delete[] thread.