473,774 Members | 2,248 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C Style Strings

Hi,

I've always used std::string but I'm having to use a 3rd party library
that returns const char*s. Given:

char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";

How do I append the contents of pString2 to pString? (giving "Blah
Blah Blah")

I looked at strcat but that crashes with an unhandled exception.

Thanks
Jun 1 '06
89 5162
On 2006-06-02, Noah Roberts <ro**********@g mail.com> wrote:

we******@gmail. com wrote:
Well hang on -- this is precisely where you can make an argument for C
over C++. In C since you are forced to do everything by hand, you have
the advantage of being able to do everything by hand. For example, you
use local stack based memory to back certain allocations if you know
that the lifetime of the resource is equal to the lifetime of the
function call. In C++ you can hope your compiler can figure it out; if
not it will use new/delete which eventually falls back to malloc/free
which is hundreds of times slower.


That statement about C++ is simply incorrect; I can't even imagine
where it is coming from.


I imagine that it comes from a basic understanding of stack-based memory.

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
You can lead a blind man to water but you can't make him chug it.
Jun 2 '06 #31

Andrew Poelstra wrote:
On 2006-06-02, Noah Roberts <ro**********@g mail.com> wrote:

we******@gmail. com wrote:
Well hang on -- this is precisely where you can make an argument for C
over C++. In C since you are forced to do everything by hand, you have
the advantage of being able to do everything by hand. For example, you
use local stack based memory to back certain allocations if you know
that the lifetime of the resource is equal to the lifetime of the
function call. In C++ you can hope your compiler can figure it out; if
not it will use new/delete which eventually falls back to malloc/free
which is hundreds of times slower.


That statement about C++ is simply incorrect; I can't even imagine
where it is coming from.


I imagine that it comes from a basic understanding of stack-based memory.


How do you figure?

Jun 2 '06 #32
On 2006-06-02, Noah Roberts <ro**********@g mail.com> wrote:

Andrew Poelstra wrote:
On 2006-06-02, Noah Roberts <ro**********@g mail.com> wrote:
>
> we******@gmail. com wrote:
>> Well hang on -- this is precisely where you can make an argument for C
>> over C++. In C since you are forced to do everything by hand, you have
>> the advantage of being able to do everything by hand. For example, you
>> use local stack based memory to back certain allocations if you know
>> that the lifetime of the resource is equal to the lifetime of the
>> function call. In C++ you can hope your compiler can figure it out; if
>> not it will use new/delete which eventually falls back to malloc/free
>> which is hundreds of times slower.
>
> That statement about C++ is simply incorrect; I can't even imagine
> where it is coming from.
>


I imagine that it comes from a basic understanding of stack-based memory.


How do you figure?


If you have stack-based memory, any memory allocated will be deallocated
by the hardware by definition when the memory is popped.

Without stack-based memory, malloc() and free() must be called (on a lower
level than C++ lets you see), which invokes the OS to manage freeing memory
and managing it.

Obviously, deallocating memory as a side effect of simply popping a stack is
many times faster than calling a function and letting the OS sort it out.

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
You can lead a blind man to water but you can't make him chug it.
Jun 2 '06 #33
Andrew Poelstra <ap*******@loca lhost.localdoma in> wrote:
On 2006-06-02, Noah Roberts <ro**********@g mail.com> wrote:

we******@gmail. com wrote:
function call. In C++ you can hope your compiler can figure it out; if
not it will use new/delete which eventually falls back to malloc/free
which is hundreds of times slower.


That statement about C++ is simply incorrect; I can't even imagine
where it is coming from.


I imagine that it comes from a basic understanding of stack-based memory.


I don't believe the complaint was about stack memory. It was about the
incorrect statement regarding C++. The same statement may be considered
valid concerning Java, C#, VB, or C++/CLI, for example; but those are
different languages from C++. (The word "valid" should be taken lightly
there; I haven't verified the hundreds of times.)

C++ perfectly well allows programmers to allocate any "objects" (not
quite, really, since they don't own their identity so they are a sort of
2/3-object... but in C++ vocab they are objects) on the stack, with all
the accompanying performance benefits.

--
Chris Smith - Lead Software Developer / Technical Trainer
MindIQ Corporation
Jun 2 '06 #34

Chris Smith wrote:
Andrew Poelstra <ap*******@loca lhost.localdoma in> wrote:
On 2006-06-02, Noah Roberts <ro**********@g mail.com> wrote:

we******@gmail. com wrote:
> function call. In C++ you can hope your compiler can figure it out; if
> not it will use new/delete which eventually falls back to malloc/free
> which is hundreds of times slower.

That statement about C++ is simply incorrect; I can't even imagine
where it is coming from.


I imagine that it comes from a basic understanding of stack-based memory.


I don't believe the complaint was about stack memory. It was about the
incorrect statement regarding C++. The same statement may be considered
valid concerning Java, C#, VB, or C++/CLI, for example; but those are
different languages from C++. (The word "valid" should be taken lightly
there; I haven't verified the hundreds of times.)

C++ perfectly well allows programmers to allocate any "objects" (not
quite, really, since they don't own their identity so they are a sort of
2/3-object... but in C++ vocab they are objects) on the stack, with all
the accompanying performance benefits.


Yes, that is what I was talking about. C++ and C do not differ in the
way it was being stated.

Jun 2 '06 #35
"kwikius" <an**@servocomm .freeserve.co.u k> wrote
scroopy wrote:
Hi,

I've always used std::string but I'm having to use a 3rd party library
that returns const char*s. Given:

char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";

How do I append the contents of pString2 to pString? (giving "Blah
Blah Blah")
#include <malloc.h>
#include <cstring>

char* concat(const char * str1, const char* str2)
{
char * result = (char*) malloc(strlen( str1) + strlen (str2) + 1);
if( result != NULL){
strcpy(result,s tr1);
strcat(result, str2);
}
return result;
}

Perfectly unexceptional code.
It won't execute as efficiently as it might, but then most programs can
manipulate a string much faster than a human can read it, however
inefficiently written.

If we want we can do a speed-up

void fastconcat(char *out, char *str1, char *str2)
{
while(*str1)
*out++ = *str1++;
while(*str2)
*out++ = *str2++;
*out = 0;
}

this is a bit of nuisance since it throws the burden of memory allocation
onto the user, it is also rather dangerous sinvce we don't check the buffer.
But it will be very fast. That's the beauty of C, you can roll the function
to the problem you face.
#include <iostream>
#include <string>

char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";
int main()
{
// C-style
char* str = concat(pString1 ,pString2);
if(str != NULL){
std::cout << str <<'\n';
free(str);
}

// C++ style
std::string str1=std::strin g(pString1) + pString2;
Ok what's going on here?
You have a string, and now you are calling what looks like a string
constructor to create another type of string. Why do you need two types of
string in the program? Do they behave differently when passed to cout? How
do I know that they will behave in the same way?
std::cout << str1 <<'\n';
}

I'm not sure if that is the optimal C method. Its interesting to note
how much better the C++ version is though!

So what's the big - O analysis of that '+' operation? Where is this
documented? What if I want to sacrifice a bit of safety for speed, as we did
with C? Can I overload the string '+' operator to achieve this?

Apologies to our friends on C++, but this was a provocative post.
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm
Jun 3 '06 #36
Malcolm posted:

If we want we can do a speed-up

void fastconcat(char *out, char *str1, char *str2)
{
while(*str1)
*out++ = *str1++;
while(*str2)
*out++ = *str2++;
*out = 0;
}

I'd say that has the potential to "run slower" than a version which uses
strcpy. A system would be more efficient copying int's than char's, so
strcpy could be implemented platform-specifically as something like:

(Unchecked code:)

inline bool NoByteZero(unsi gned const v)
{
return ( ( (v & 0x7F7F7F7F) + 0x7F7F7F7F ) | v ) | 0x7F7F7F7F;
}

void strcpy(char *pdest, const char *psource)
{
int *idest = reinterpret_cas t<int*>(pdest) ;
int *isource = reinterpret_cas t<int*>(psource );

for ( ; NoByteZero(*iso urce); *idest++ = *isource++);

char *cdest = reinterpret_cas t<char*>(idest) ;
char *csource = reinterpret_cas t<char*>(isourc e);

while( *cdest++ = *csource++ );
}

(This code makes the presumption that on the given platform, it's okay to
access memory which isn't yours.)
-Tomás
Jun 3 '06 #37
Malcolm wrote:
"kwikius" <an**@servocomm .freeserve.co.u k> wrote void fastconcat(char *out, char *str1, char *str2)
{
while(*str1)
*out++ = *str1++;
while(*str2)
*out++ = *str2++;
*out = 0;
}

this is a bit of nuisance since it throws the burden of memory allocation
onto the user, it is also rather dangerous sinvce we don't check the buffer.
You are joking right?
But it will be very fast. That's the beauty of C, you can roll the function
to the problem you face.
The whole point is that you cant. C doesnt give you the tools.

[..]
// C++ style
std::string str1=std::strin g(pString1) + pString2;

Ok what's going on here?
You have a string, and now you are calling what looks like a string
constructor to create another type of string.


It is the same type.

Why do you need two types of string in the program? Do they behave differently when passed to cout? How
do I know that they will behave in the same way?

std::cout << str1 <<'\n';
}
They are the same type
I'm not sure if that is the optimal C method. Its interesting to note
how much better the C++ version is though!
So what's the big - O analysis of that '+' operation? Where is this
documented?


Its part of the C++ standard library.

What if I want to sacrifice a bit of safety for speed, as we did with C? Can I overload the string '+' operator to achieve this?
Sure, as long as it doesnt clash with overloads defined in the C++
standard.
Apologies to our friends on C++, but this was a provocative post.


Sorry if the post was provocative. C is a wonderful language and I will
have to get back to it some time.

regards
Andy Little

Jun 3 '06 #38
On Thu, 1 Jun 2006 21:31:58 +0100, "Malcolm"
<re*******@btin ternet.com> wrote:
"kwikius" <an**@servocomm .freeserve.co.u k> wrote
scroopy wrote:
Hi,

I've always used std::string but I'm having to use a 3rd party library
that returns const char*s. Given:

char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";

How do I append the contents of pString2 to pString? (giving "Blah
Blah Blah")


#include <malloc.h>
#include <cstring>

char* concat(const char * str1, const char* str2)
{
char * result = (char*) malloc(strlen( str1) + strlen (str2) + 1);
if( result != NULL){
strcpy(result,s tr1);
strcat(result, str2);
}
return result;
}

Perfectly unexceptional code.
It won't execute as efficiently as it might, but then most programs can
manipulate a string much faster than a human can read it, however
inefficientl y written.

If we want we can do a speed-up

void fastconcat(char *out, char *str1, char *str2)
{
while(*str1)
*out++ = *str1++;
while(*str2)
*out++ = *str2++;
*out = 0;
}

Why do you believe that manually stepping through each character will
be faster when strcpy and strcat can take advantage of any CISC
instructions the hardware might offer?
Remove del for email
Jun 3 '06 #39
In article <5u************ *************** *****@4ax.com>,
sc******@doezl. net says...

[ ... ]
strcpy(result,s tr1);
strcat(result, str2);

[ ... ]
If we want we can do a speed-up

void fastconcat(char *out, char *str1, char *str2)
{
while(*str1)
*out++ = *str1++;
while(*str2)
*out++ = *str2++;
*out = 0;
}

Why do you believe that manually stepping through each character will
be faster when strcpy and strcat can take advantage of any CISC
instructions the hardware might offer?


The first method steps through the first string once (in
strcpy) to copy it, and then again (in strcat) to find
its end, before concatenating the second string onto it.

His method avoids stepping through the first string the
second time.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 3 '06 #40

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
8323
by: Christopher Benson-Manica | last post by:
I have a C-style string (null-terminated) that consists of items in one of the following formats: 14 characters 5 characters space 8 characters 6 characters colon 8 characters 5 characters colon 8 characters Items are delimited by semicolons or commas. I have to produce a string delimited only by semicolons and containing items in the first two formats only. For example,
5
2427
by: Curtis Gilchrist | last post by:
I am required to read in records from a file and store them in descending order by an customer number, which is a c-style string of length 5. I am storing these records in a linked list. My problem is in comparing the customer number I just read in with those in the list. I'm not sure how to go about comparing c-style strings for greater than, less than.. here is how I am currently trying to do it: while( ( custinfo.number >...
3
2120
by: joealey2003 | last post by:
Hi all... I included a css file on my html and i need to check some properties. The html is: <style id="myid" src="mycsspage.css"> </style> Now i need something to access it like: alert(document.getElementById("myid").bottomline.color);
7
1952
by: seans | last post by:
Hi, I need to change the font, font size, and color of a button on a form. I need to save the current style settings and restore them later. Is there an easy way of doing that? Sorry if there is a simple solution to this; I am still learning Javascript. Thanks again.
5
10228
by: Chuck Bowling | last post by:
Maybe I'm doing something wrong or just don't understand the concept, but i'm having a problem with default properties. My impression of how a default property should act is this; MyClass c = new MyClass(); c = "my text"; In the line above, the string is assigned to a field in the class instance.
2
1418
by: Xiaoshen Li | last post by:
Dear All, I hear a lot that cstring cannot be changed. But my code: /************************************************************* * Testing cstring(a pointer) * **********************************************************/ #include <iostream> using namespace std;
4
2013
by: Kza | last post by:
Hi, just in the process of maintaining some software that used some funy old string library and char*s , and we are updating everything to use std::strings. (or should I say std::basic_string<>s) I find it wierd that that all the new c++ ansi style librarys like the streams and file handling classes still expect us to use old style char* type strings. For example, ofstreams open function expects the filename as a char* parameter rather...
2
2227
by: Kamjah Kogumah | last post by:
A Dev Opera article suggest using code 2 instead of code 1 in performance-critical functions. code 1: a += 'x' + 'y'; code 2: a += 'x'; a += 'y';
16
3674
by: yu_kuo | last post by:
Is there any comparison data on perfomance difference between std::string and c style string? Or maybe if there are source code which could be used to measuer on different compiler/platform, in a systematic way?
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8939
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2852
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.