473,698 Members | 2,603 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is C-style string unchangable?

Dear All,

I hear a lot that cstring cannot be changed. But my code:

/*************** *************** *************** *************** *
* Testing cstring(a pointer)
* *************** *************** *************** *************/
#include <iostream>
using namespace std;

int main()
{
char shortsTring[] = "abc";
shortsTring[2] = 'X';

cout << shortsTring << endl; //print out abX !!!

return 0;
}

So why many people are saying cstring cannot be changed? Could you help
me? Thank you very much.

Dec 30 '05 #1
2 1411

"Xiaoshen Li" <xl**@gmu.edu > wrote in message
news:dp******** **@osf1.gmu.edu ...
Dear All,

I hear a lot that cstring cannot be changed.

If by 'cstring' you mean the 'C-style string', i.e. a zero-terminated
array of characters, then you heard wrong. For various reasons, *some*
C-style strings are not modifiable in a defined way. To state this about
*any* such string is simply wrong.

What cannot be modified is an array whose elements are const:

const char arr[] = "Attempts to modify this string"
" should result in compiler diagnostic";

or a string literal:

char *p = "I am a literal";

p[0] = 'i'; // undefined behavior.
But my code:

/*************** *************** *************** *************** *
* Testing cstring(a pointer)
There are no pointers declared or defined in your code.
* *************** *************** *************** *************/
#include <iostream>
using namespace std;

int main()
{
char shortsTring[] = "abc";
This is an array of four type 'char' objects. It is not a pointer.
shortsTring[2] = 'X';
This replaces the object at shortsTring[2] with the character value 'X'
The string now contains: "abX"

cout << shortsTring << endl; //print out abX !!!
This is expected and normal behavior. You created a 'normal'
non-const (i.e. modifiable) array of characters, changed the
value of one of those characters, then inserted all the characters
into the output stream designated by 'cout'.

Which C++ book(s) are you reading?

return 0;
} -
So why many people are saying cstring cannot be changed?
Two possibilites:
1. They're simply wrong.
2. You've misunderstood.

Depending upon context, some objects are modifiable, others are not.
The types of these objects (such as char, or arrays thereof), makes
no difference.
Could you help me? Thank you very much.


The best help I can offer is to advise you to abandon the use
of character arrays for representing strings in C++, and use
the 'std::string' type (declared by <string>), which was created
specifically for the purpose.

-Mike
Dec 30 '05 #2
"Xiaoshen Li" <xl**@gmu.edu > wrote in message
news:dp******** **@osf1.gmu.edu ...
Dear All,

I hear a lot that cstring cannot be changed. But my code:

/*************** *************** *************** *************** *
* Testing cstring(a pointer)
* *************** *************** *************** *************/
#include <iostream>
using namespace std;

int main()
{
char shortsTring[] = "abc";
shortsTring[2] = 'X';

cout << shortsTring << endl; //print out abX !!!

return 0;
}

So why many people are saying cstring cannot be changed? Could you help
me? Thank you very much.


constant "cstring" (c style strings) can not (should not) be changed. It is
fine to change non constant c style arrays as you've seen.

Whoever told you that all c style strings can not be changed was simply
wrong. A C style string is simply an array of characters which is null (0)
terminated. Nothing more, nothing less. You can change the data just as
you can change any array data.

Note the difference between:
char* shortsTring = "abc"; // shortsTring points to constant data
and
char shortsTring[] = "abc"; // shortsTring is an array of non constant data


Jan 2 '06 #3

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

Similar topics

16
6738
by: Krakatioison | last post by:
My sites navigation is like this: http://www.newsbackup.com/index.php?n=000000000040900000 , depending on the variable "n" (which is always a number), it will take me anywhere on the site... this number is always changing as I have hundreds of thousand of pages of text on my site. Problem: - in my opinion this just not only look weird, but the variable "n" (number)
5
31176
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it will split myString up using the delimiter of 1 space so that
9
8000
by: John F Dutcher | last post by:
I use code like the following to retrieve fields from a form: recd = recd.append(string.ljust(form.getfirst("lname",' '),15)) recd.append(string.ljust(form.getfirst("fname",' '),15)) etc., etc. The intent is to finish by assigning the list to a string that I would write to disk: recstr = string.join(recd,'')
9
3693
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people discuss how reflection does this, but I cannot find the syntax to do this. I have tried several code example off of gotdotnet and other articles. Can somebody please show me the code to do this?
9
18425
by: Lans | last post by:
I have a string that I need to tokenize but I need to use a string token see example i am trying the following but strtok only uses characters as delimiters and I need to seperate bu a certain word char *mystring "Jane and Peter and Tom and Cindy" char *delim = " and "; char *token; token = strtok(mystring, delim);
10
8168
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That said, is there any real reason why I can't derive an otherwise empty
1
16341
by: Thomas | last post by:
It looks like the String.replace doesn't work in IE6.1. Anyone else has the same problem. I am using newest service package of IE and Win2K. Thanks
22
3248
by: Michael Rasmussen | last post by:
Hi all, Not sure if this is OT? I have a function in a library written in C++ which returns a strdup(s.c_str()) to an application written i C. Running Valgrind on my C-application shows this results in memory leaks due to the c_str is never freed. Example:
4
1948
by: lyealain | last post by:
beginner here..hahahha... how can i change the textbox become unchangable ar>??? can see but cannot change...
0
8680
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
9169
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...
1
8899
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7738
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
6528
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
5861
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
4371
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
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2007
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.