views:

108

answers:

3

I have some C++ code that I found that does exactly what I need, however I need it in C and I do not know how I could do it in C, so I am hoping someone can help me out.

The C++ code is:

std::string value( (const char *)valueBegin, (const char *)valueEnd );

This is using the string::string constructor:

template<class InputIterator> string (InputIterator begin, InputIterator end);

Can anyone help me in converting this to C code?

Thanks!

A: 

The C++ code creates new string from substring of another string. Similiar functionality in C is strndup:

char *str = strndup(valueBegin, valueEnd - valueBegin);
// ...
free(str);
Messa
strndup is a GNU extension.
R Samuel Klatchko
+7  A: 
// Get the number of characters in the range
size_t length = valueEnd - valueBegin;

// Allocate one more for the C style terminating 0
char *data = malloc(length + 1);

// Copy just the number of bytes requested
strncpy(data, valueBegin, length);

// Manually add the C terminating 0
data[length] = '\0';
R Samuel Klatchko
The `malloc()`'d memory will need to be `free()`'d as well.
mskfisher
Works perfectly! Thank you!
kdbdallas
Also to not cause a warning the second parameter of strncpy needs to be casted to: (const char *)
kdbdallas
@kdbdallas - what is the type of valueBegin? I assumed it was a `char *` which would mean you shouldn't need a cast for strncpy. If it is not a `char *` or `const char *`, you may need to reevaluate the subtraction in the first ine.
R Samuel Klatchko
A: 

By assuming that pointer arithmetic make sense in your situation:

strncpy( value, valueBegin, valueEnd-valueBegin );
Martin Cote
His example creates `value` as an automatic variable, but you're assuming `value` is a pointer to valid memory.
mskfisher