You are here:

C++/adding a string to a char array



I've searched the net and posted this question to a forum, but still haven't got a usefull solution.
My problem is that I have to add a variable (int, string, double) to a character array. I know that it is very easy with Java but I din't find any thing for C/C++.
Everything I found created errors.

bool Tektronix::setOffset(int arg1){
   char msg[] = "source1:Voltage:Offset " + arg1; //this is  Java way
   status = viWrite(vi, (ViBuf) msg , sizeof(msg), &retCnt);
   if (status < VI_SUCCESS) return false;

I've added the first 4 lines of my methode "setOffset(int arg1)". "msg" is the char array created at the beginning of the methode it's very importend that the size of this array is equal to the size of the hardcoded line + the length of arg1, because it is used in the "viWrite(.....)".
viWrite is a methode written by VISA (National Instuments). I only can convert a char array to a ViBuf what is needed in viWrite.

the following typedef is made in Visatype.h
     typedef unsigned char       ViByte;
     typedef ViByte      _VI_PTR ViPByte;
     typedef ViPByte          ViBuf;

I have tried many ways including making strings en converting these to a char array but than the array size is not correct (allways 32 instead of ex. 10). I need a solution that I can merge some data, resulting in a char array with the exact size of the two data "strings" together.

I hope you can help me, if there are things you don't understand please let me know and I wil try to explain them.

thanks in advance


OK. First off char arrays are the C-style way of handling strings. A C-string is an array characters (char) terminated by a zero value character.

The C language has very little built in support for such strings. It supports string literals which can be used as initialisation for char arrays or for initialisation of pointers to char (C - and thereby C++ - has a close relationship between array types and pointer types - the name of an array is equivalent to a pointer to its first element).

Instead the standard C library provides support for manipulating the zero terminated char array C strings in the form of a set of functions which have the prefix str. So for example if you wish to find the length of a C-string you use strlen( c_string ). Note that strlen counts the number of characters up to but not including the terminating zero, thus you can have a larger amount of space allocated for a string than is being used:

   char str[128];  // allocate array for string up to 127 characters
   str[0] = '\0'; // terminate on first character
   size_t str_length = strlen(str);   // str_length == 0
   size_t str_buf_size = sizeof(str); // str_buf_size == 128

If you wish to append one C-string to another you need to use strcat:

   strcat( string1, string2 );

The above statement will append (concatenate) string2 to the end of string1. However there is a caveat - a very big caveat for someone coming from an environment like Java: strcat does _not_ do any allocation of additional memory required to hold the additional characters appended to string1, thus you have to ensure that the buffer used to hold string1 is already large enough to hold the sum of strlen(string1) + strlen(string2) + 1. The + 1 at the end of that calculation is for the terminating zero. If the appending of characters from string1 exceeds the allocated memory available in string1 then you will overwrite memory. If you are lucky this will cause an immediate crash. If not it will likely cause weird errors possibly some time after the cause of the problem and be much harder to locate and fix.

You therefore often re-build two such strings into a third:

   strcpy( result, string1 );
   strcat( result, string2 );

The result object is a char array at least of size strlen(string1) + strlen(string2) + 1. The strcpy function is similar to strcat except that it copies string1 to (the front of) result (thus overwriting anything that was previously in result).

This brings up another problem. The statement:

   char msg[] = "source1:Voltage:Offset " + arg1;

Cannot ever work in C or C++, even if the + operator was defined as concatenation for C-string char arrays, and the compiler automatically converts a number to a C-string for you. This is because it defines a statically sized (i.e. size is calculated and memory allocated during compilation) array and the compiler cannot know the value of the runtime valued variable arg1. It also will allocate memory directly on the stack frame of the function call. This is unlike Java and similar languages where the "built in" string type is just a synonym for a language support class java.lang.String or similar, and is therefore not a value type but a reference type whose memory is _always_ allocated dynamically from the heap (a.k.a. free store etc.).

You really need to step back and read up on the differences between platforms like Java and .NET and languages such as C and C++. Sorry but I do not have the time to do this for you.

OK you will notice that I have said much about C and very little about C++. This is because your first example is a C-style example. You have to include <string.h> (for C) or <cstring> (for C++) to use the C-string library functions (note that C++ has a very good compatibility with C and this includes supporting the C standard library facilities).

Now you have tried to use the C++ std::string (or something similar, you do not say exactly which strings you used). Note that standard library names are placed in the std namespace and C++ uses :: rather than . to separate parts of a qualified name (thus java.lang.String would be java::lang::String using C++ syntax). If you just convert such an object to a char array - or a pointer to such an object to a pointer to char then you are going to get silly results. The std::string type is a C++ class type and it will contain information other than the character data (or pointer to the character data) of the string. Just converting it to a char * will make the data members of the std::string object appear as a sequence of characters, exactly how the internals of std::string are implemented varies between implementations - thus the implementation supplied with the MS Visual C++ compiler will be different from that supplied with say the GNU g++ compiler.

   std::string str("source1:Vo"); // 10 characters
   // sizeof(str) is probably _not_ 10

The correct way to obtain access to the data of a std::string is to use the c_str operation (or in rare cases the data operation). The good thing about the C++ std::string class is that it does support the kind of operations you are trying to achieve, + and += for concatenation, size or length operations for the character length (size and length are synonyms - they do the same thing), etc.

Putting this together we have:

   #include <string>  // include header for std::string et al

   // ...

   std::string msg("source1:Voltage:Offset ");

   msg += arg1_as_a_string;

   status = viWrite(vi, msg.c_str(), msg.size(), &retCnt);

   if (status < VI_SUCCESS) return false;

There are a some things to note about the above:

First, to use std::string and related types and functions you include the <string> header.

Next, as before, I declare an object of type std::string called msg and initialise it with the constant literal part of the msg string from your example.

The msg object is created on the stack. Internally it may well use dynamically allocated memory, but the object itself is a value object on the stack frame of the function call. This also means that it will be destroyed when it goes out of scope - no later than return from the function. In this case its destructor will be called that will release any held resources such as dynamically allocated memory for the characters of the string - this has to be written explicitly in the destructor implementation. C++ has (at present) no garbage collection and uses deterministic destruction of objects. In particular local stack object are destroyed when they go out of scope which is never later than when leaving the function call - either normally via a return statement (or end of function) or exceptionally via a thrown exception.

On the next line after creating and initialising a local string object I append the value of the arg1 number. However converting a number to a string and then appending the string to a std::string is not directly supported so I have assumed that arg1 was converted to a string form elsewhere and the string form stored in an object called arg1_as_a_string for the moment.

Next I pass the character data in the msg std::string object to the viWrite function you show. Here I use the operations provided by the std::string class for such purposes. The size operation: msg.size() returns the number of characters in the string. Note that std::string objects are not required to store a terminating zero, nor are they required to store all the characters of the string in one contiguous block of memory. So to get the string value as a C-string the c_str operation is provided: msg.c_str(). Note that the returned pointer to char is a pointer to const char - i.e. the contents are not modifiable. This is because the string object owns the data pointed to. One specific point about c_str is that it will return a pointer to a char array buffer with a terminating zero. If this is not required as may be the case here as you pass the size of the buffer as well you could try using the data operation instead: This returns the string character data as a pointer to const char to a char array without a terminating zero. As with the c_str operation you cannot modify the contents pointed to and the string object owns the array.

Note: ownership implies the owner will release the owned resource when it is destroyed. Thus when msg is destroyed any pointers to buffers returned by c_str or data become invalid.

To convert a number to a string we can use a string stream. These work like other streams, such as file streams, except they read or write from or to strings rather than files. In this case we use a std::ostringstream - an output string stream, thus writing to such a stream writes characters to a string. The useful thing about C++ IOStreams is that they have built in formatting operations for fundamental types: integer types, floating point types, bool as well as char * (assumes a zero terminated C-string) and std::string etc. (and user defined types can implement overloaded operators to output formatted versions of their objects).

Thus where we can say:

   std::cout << arg1;

And get the value of arg1 displayed on the console as a sequence of decimal digit characters so we can use:

   out_str_stream << arg1;

To write the same sequence of decimal digit characters into the string associated with out_str_stream. Thus following on from the previous example let us initialise arg1_as_a_string with the data in out_str_stream, converting arg1 to a string:

   #include <sstream>

   // ...

   std::ostringstream out_str_stream;
   out_str_stream << arg1;

   std::string arg1_as_a_string(out_str_stream.str());

One advantage of this approach is that if you do not like the default formatting of the number you can always apply different formatting options to the stream either to the stream as a whole or on an item by item output basis:

   #include <iomanip>


   out_str_stream << std::setw(10) << arg1;

The above use of std::setw sets the width of the arg1 number field to at least 10, with a default fill character of a space, thus 12345 would appear as ^^^^^12345 where ^ represents a space.

Note that the code I have shown is for example purposes only and should not be considered of production quality - I have left out error checking for example. It also may contain the odd typo - if so I apologise.

I have only given you the 2 minute tour around the issues directly concerning your question. There is much more that you should be aware of which I do not have time to teach you here - this is not the forum for extended training and it is not my forte in any case (I am not a professional educator). As it is this answer has taken an hour or two out of my day to write for you. The rest is up to you...

...However here is some advice:

If you are using C++ then I strongly advise you to obtain some good texts and references on C++ and the C++ standard library. C++, although having some syntactic similarity to Java is a _very_ different beast and you need to understand the differences.

From the look of your work you also need to understand C. Note that C is sometimes called a high level assembler. Bear this in mind!

I would advise you to learn good C++ practice and use the facilities of the C++ library and language wherever possible and only drop into C where required - as I have done in my example using std::string.

Here are some books and other resources you might like to look at:

People often recommend the following if you already have some programming experience (as you seem to have):

"Accelerated C++" by Koenig and Moo

although I have not read this.

There are many books on programming in general that are good. I found

"The Practice of Programming" by Kernighan and Pike

to be particularly useful.

For general good C++ usage you should look at

"Effective C++" "More Effective C++" and "Effective STL" by Scott Meyers

and the more advanced

"Exceptional C++" and "More Exceptional C++" and "Exceptional C++ Style" by Herb Sutter (See also
"Modern C++ Design" by Andrei Alexandrescu
"Ruminations on C++" by Koenig and Moo
"C++ Coding Standards" by Herb Sutter and Andrei Alexandrescu

For C++ reference you should look at:

"The C++ Programming Language" 3rd Ed. or special edition by Bjarne Stroustrup

the C++ reference book from the man himself. You should also take a look at his book "The Design and Evolution of C++".

In addition you will most likely find that a couple of additional reference works will be of use. For the standard C++ library there is:

"The C++ Standard Library - a Tutorial and Reference" by Nicolai M. Josuttis - one of my most referred to books.

and for C++ templates there is:

"C++ Templates the Complete Guide" by David Vandevoorde and Nicolai M. Josuttis.

For C reference I use the classic book "The C Programming Language" by Brian W. Kernighan and Dennis M. Ritchie. If fact this is quite a good book to learn C from if you have some programming experience already.

The final reference works I am going to recommend are the C++ and C standard documents themselves which are published in book form by Wiley or are available for download as a PDF from the ANSI web site for $30 US (price the last time I checked):

"Programming Languages - C++" and "Programming Languages - C"

the books are just titled:

"The C++ Standard" and "The C Standard"

These are _not_ easy reads, but are the word on how a C++ or C implementation should behave (note I say should behave, not do behave!).

These are just some of the books I have found (or read reviews that suggest they are) useful and are in no way a complete list. I suggest you try to find a real book shop that stocks at least some of these titles to see if any of them are for you. Alternatively you could look for reviews on the internet. One good place for book reviews is the ACCU site at, specifically

As to web sites on the internet, there are many articles on all sorts of technical things and there are many tools, applications and libraries available for free that can be downloaded. Most often a few minutes with a search engine (e.g. Google at can turn up the information you require. Here are just a few sites I know of (again biased towards C++):

There is a decent C++ FAQ at Posters of questions to the comp.lang.c++.moderated newsgroup are supposed to refer to this FAQ before they post a question as it answers a lot of the basic questions that are asked repeatedly.

There are various articles at They seem to have a C++ tutorial but I have not read it.

There is some online documentation for some parts of the C++ standard library at However it should be noted that some of this documentation concerns SGI specific non-standard extensions to the standard C++ library.

There are a few papers on C++ at The paper on function pointers is also partially applicable to C.

As already mentioned the site of the ACCU, an organisation for professionalism in programming, at has many book reviews. It also has many resource links to web sites that may be of interest to you at If you become a member you have access to mailing lists and mentored projects (which are run from time to time) among other benefits.

Finally I would like to point out that there are several encyclopaedia sites on the web. One of the best is Wikipedia at The article on the C programming language is at and C++ at (oddly searching for "C++ programming" does not get you where you would think, its just titled "C++"). You will note that many of the articles have useful cross links to other Wikipedia articles and other web sites.

Hope this is of some use to you.  


All Answers

Answers by Expert:

Ask Experts


Ralph McArdell


I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.


My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at


©2017 All rights reserved.