473,800 Members | 2,518 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 5171
"persenaama " <ju***@liimatta .org> writes:
we******@gmail. com wrote:
Ok -- using syntax and concepts from C++ that are not just directly
lifted from C, how does one make a static CBString such as I have
shown? (You can drop the static decorator in the front, to make this
all just about the stack, and not static memory.)


void foo()
{
static const char * x = "hi";
}

void bar()
{
const char * y = "hi";
}

The difference between foo() and bar() is that the pointer object y is
in the stack while the pointer object x isn't. The string literal isn't
in the stack in either case.

However, in C++, you cannot really say that as there is no concept of
stack in C++ it is just commonly understood that a stack is a very
practical and common implementation of local scoped objects with auto
storage within a function.

I think I have to re-read what this was really about as I seem to miss
the point what stack has to do with the string literal. :)


C has no concept of "stack" either; the word appears nowhere in the C
standard. Objects with automatic storage duration are commonly
allocated on something called a "stack" (i.e., a contiguously
addressed chunk of memory that grows and shrinks in a stack-like
manner), and their lifetime follows stack-like last-in first-out
behavior. But it's entirely legal, and not unheard of, for the local
variables of a function to be allocated from a "heap" (also a word
that appears nowhere in the C standard).

I *think* it's exactly the same in C++, but I'm less familiar with it
than I am with C.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 4 '06 #71

persenaama wrote:
I think I have to re-read what this was really about as I seem to miss
the point what stack has to do with the string literal. :)


I've been trying to follow this guy's line of reasoning from the moment
he said C and C++ implementations where different wrt the stack and
local variables and even at that I can't figure out wtf he is talking
about. If you figure it out, let me know.

Jun 5 '06 #72

<we******@gmail .com> skrev i meddelandet
news:11******** **************@ g10g2000cwb.goo glegroups.com.. .
Noah Roberts wrote:
[...] What I think they all
mean just looking at the above would result in exactly the same
operations.
Conceptually, they are, but by implementation they are not. In
particular there is no way to trick the C++ part into constructing
the
contents of the string form purely stack or static memory unless you
actually use the C syntax.


Of course there is!
[...] Of course there is nothing requiring that CBString be
implemented so that += does not accept a const char* directly.
Right, but it doesn't help, because you still need to call an extra
strlen(). (Or iterate character by character but you don't get to
leverage the compiler's highly optimized memcpy().)


And what makes you think that the C++ compiler cannot compute
std::strlen("Hi ") at compile time? Or optimize memcpy for a constant
size parameter?

Mine sure does!
Even at that.... your code example does not prove your point at
all.
It does not illustrate any difference between C and C++ with regard
to
stack variables.


Ok -- using syntax and concepts from C++ that are not just directly
lifted from C, how does one make a static CBString such as I have
shown? (You can drop the static decorator in the front, to make
this
all just about the stack, and not static memory.)


It doesn't have to use any static or macro tricks, just properly
optimize the normal std::string.
Bo Persson
Jun 5 '06 #73

"Phlip" <ph******@yahoo .com> wrote in message
news:bx******** ***********@new ssvr13.news.pro digy.com...
Ian Collins wrote:
Profiling isn't just about determining which low-level bits to split.

Who said it was?


Take a cleansing breath, Ian. Sometimes when a post contains a quote, the
next line doesn't contradict but reinforces it. I'm aware this is the
exception with USENET, but it happens.

In this case, the mark you replied to took the position "optimizati on is
about opcodes, so profiling won't work for portability".

No the "mark", actually a Malcolm, said that profiling is about opcodes, or
more or less.

I can count the number of lines a procedure executes without a profiler. In
fact no profiler I know will give me a big O analysis of an algorithm
directly.
What I can't do without inordinate difficulty is determine exactly how long
each operation takes.
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm

Jun 5 '06 #74
On Mon, 05 Jun 2006 11:15:47 +1200, I waved a wand and this message
magically appeared from Ian Collins:
Seems I was incorrect, the routine is strlen() which actually
counts 4 bytes at a time and returns the total asciiz string length.


Something like:

http://cvs.opensolaris.org/source/xr...en/strlen.s#27


Yes, that's quite similar.
--
http://www.munted.org.uk

Take a nap, it saves lives.
Jun 6 '06 #75
Noah Roberts wrote:
we******@gmail. com wrote:
Even at that.... your code example does not prove your point at all.
It does not illustrate any difference between C and C++ with regard to
stack variables.
Ok -- using syntax and concepts from C++ that are not just directly
lifted from C, how does one make a static CBString such as I have
shown?


Ok, I see where the difference is in the two code segments. You are
mistaking the stack for static variables apparently. Nothing keeps you
from doing this:

void f(CBString & str)
{
static CBString hi = "hi";

str += hi;
}


Right but this is a static, and it executes a construction at init
time.
Besides that I fail to understand what exactly it is you think is
different.
Uhh ... strlen(), etc is called one way or another for CBStrings is
all. I am not a C++ person, so I neglected to consider that C++ allows
for additional init-time function calls (the older portable C standard
doesn't allow this). A static construction, essentially removes the
resource issue, so this makes the point of my example moot.
[...] I have no idea what your functions do beyond your poor
attempt to describe them so there is no way to tell what you are
talking about.
Right ... if only they were open source and documented ... oh wait,
they are.
[...] Simply put, you are completely mistaken about there
being no way to put a variable of any kind on the "stack" in C++. I
don't know how else to put it if you don't understand that. I still
can't figure out why you think otherwise.


Whatever dude. What I am saying is the construction implicitely calls
new/delete (or equivalent) which cannot make a language or runtime
based distinction between a string literal and a string. So, using C
and preprocessor tricks, creating auto-initialization contents with
string literals (that cannot be string variables) is possible. In C++
because construction/destruction is uniform, you can pay a penalty from
extra flags, or are forced to find some other solution to pull the same
sort of trick.

bsStatic(s) is defined as follows:

#define bsStatic(s) { -__LINE__, sizeof("" s "")-1, "" s ""}

(or something like that, I am at a cyber cafe right now so its not
worth it to check it.) As you can see, this takes a string literal,
not a string variable, and it is just a compile time constant
construction. So you can just throw this into a stack variable, and
not worry about when it is going to be deleted, or freed or whatever.
(As a small point, if its non-static, a pure C compiler can fill this
into the auto-variable without holding a static copy in memory. Like,
s.mlen = -__LINE__; s.slen = 0; s.data = ""; without holding the
{-__LINE__, 0, ""} anywhere in memory.)

The use of static in C++ looks like an acceptable alternative stand in
in practice, obviously; presumably, delete need never be called on it.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Jun 6 '06 #76

we******@gmail. com wrote:
What I am saying is the construction implicitely calls
new/delete (or equivalent)


No, it doesn't. Construction of an object in no way implies new.
Construction of an object will only make a call to new if the object
allocates something on the heap. This again, is no different that in
C. It has nothing to do with the compiler...the programmer is in
complete control here.

In other words, you are just plain wrong.

Jun 6 '06 #77

<we******@gmail .com> skrev i meddelandet
news:11******** **************@ f6g2000cwb.goog legroups.com...

Whatever dude. What I am saying is the construction implicitely
calls
new/delete (or equivalent) which cannot make a language or runtime
based distinction between a string literal and a string. So, using
C
and preprocessor tricks, creating auto-initialization contents with
string literals (that cannot be string variables) is possible. In
C++
because construction/destruction is uniform, you can pay a penalty
from
extra flags, or are forced to find some other solution to pull the
same
sort of trick.


No, no, no. :-)

You are just retelling the old stories about the bloated C++ against
the fast, small, optimal C language. This is what makes the fuel of
the language wars!

My favourite test involves these two C++ strings, construct one from a
literal, and copy it to another (only works for short literals):

std::string whatever = "abcd";

0040276A mov eax,dword ptr [string "abcd" (434734h)]
0040276F mov dword ptr [esp+28Ch],eax
00402776 mov byte ptr [esp+2A7h],bl
0040277D mov dword ptr [esp+2A8h],ebp
00402784 mov byte ptr [esp+290h],bl

std::string whatever2 = whatever;

0040278B mov dword ptr [esp+33Ch],eax
00402792 mov byte ptr [esp+357h],bl
00402799 mov dword ptr [esp+358h],ebp
004027A0 mov byte ptr [esp+340h],bl
Actual assembly code from the free VC++ Express Edition. Check out the
code bloat!
Or try this larger example of where C++ templates runs *much* faster
than optimized C code:

B. Stroustrup "Learning Standard C++ as a New Language"

http://www.research.att.com/~bs/new_learning.pdf
Bo Persson
Jun 7 '06 #78
Bo Persson schrieb:
<snip>
Or try this larger example of where C++ templates runs *much* faster
than optimized C code:

B. Stroustrup "Learning Standard C++ as a New Language"

http://www.research.att.com/~bs/new_learning.pdf


Note: "Optimized C Code" is misleading in this case.
You probably meant "Simple C code compiled at highest optimization
level" -- I initially understood "C code tailored to the specific
task, profiled and hand-optimized" :-)
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jun 7 '06 #79

"Michael Mair" <Mi**********@i nvalid.invalid> skrev i meddelandet
news:4e******** *****@individua l.net...
Bo Persson schrieb:
<snip>
Or try this larger example of where C++ templates runs *much*
faster than optimized C code:

B. Stroustrup "Learning Standard C++ as a New Language"

http://www.research.att.com/~bs/new_learning.pdf


Note: "Optimized C Code" is misleading in this case.
You probably meant "Simple C code compiled at highest optimization
level" -- I initially understood "C code tailored to the specific
task, profiled and hand-optimized" :-)


Sorry about that. I really meant "Using the highly optimized functions
of the C standard library". :-)

The theme of the paper is of course that C++ can (sometimes :-) run 5
times faster than C, *without* resorting to application specific
coding, profiling, or hand-optimized code. You just use:

std::sort(buf.b egin(), buf.end());

and the compiler will expand the sort template, and inline functions
as appropriate. You just cannot do that with qsort.
My claim was that the same effect can be seen for std::string.
Sometimes it is much faster that C-style string functions, because the
compiler does some of the work at compile time.

In my particular case, and with some lucky constant propagation from
preceding code, this string constructor results in 5 assembly
instructions:

__forceinline
basic_string(co nst value_type* _String,
const allocator_type& _Allocator =
allocator_type( ) ) : _Parent(_Alloca tor)
{
const size_type _StringSize = traits_type::le ngth(_String);

if (_MySmallString Capacity < _StringSize)
{
_Construct(_Str ing, _StringSize);
}
else
{
traits_type::co py(_MySmallStri ng._Buffer, _String,
_StringSize);

_SetSmallString Capacity();
_SetSize(_Strin gSize);
}
}

------

std::string whatever = "abcd";

0040276A mov eax,dword ptr [string "abcd" (434734h)]
0040276F mov dword ptr [esp+28Ch],eax
00402776 mov byte ptr [esp+2A7h],bl
0040277D mov dword ptr [esp+2A8h],ebp
00402784 mov byte ptr [esp+290h],bl
Not bad for a code bloating template! :-)
Bo Persson
Jun 7 '06 #80

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
2428
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
2121
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
1953
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
10230
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
2228
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
3676
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
9690
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9550
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
10273
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
10032
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...
1
7574
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...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2944
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.