How do i reset a string?
I just want to empty it som that it does not contain any characters
Say it contains "hello world" at the time...
I want it to contain "". Nothing that is..
Thanx
Nov 14 '05
22 17208
On 2004-03-06 13:22:24 -0600, Tor Husabø <to***@student. hf.uio.no> said: char *str does not become a constant! It's "hello" that is "constant" (in the sense that modifying it is has undefined behavior, even if it might work on your implementation) .
This is allowed, however:
char other_string[] = "goodbye"; char *str="hello"; str = other_string;
now str points to "goodbye", and "hello" is just wasted memory, since you dont have the address anymore.
Oh yea i read the faq, thanks a lot for pointing me there..
So, as the faq says
- A string literal can be:
- An array initializer
- An unamed static array of chars
So my question its:
if i declare:
char *myString="What ever";
and later in the code:
myString="Anoth er Static Array of chars";
the pointer value will be the same ?
i mean:
"Another Static Array of chars" will start on the same memory address
than "Whatever" ?
Another questions
If i:
char *MyString1="Dog ";
char *MyString2="Cat ";
MyString1=Mystr ing2;
What happens with the initial memory referenced by MyString1 (Dog), it
remains on the memory (wasted memory) or it gets cleared in some way ?
Thanks for your helpful answers, im learning.
In article <news:c2******* ******@ID-86516.news.uni-berlin.de>
Adrian de los Santos <de*********@de mon.com.mx> writes: So, as the faq says
- A string literal can be: - An array initializer - An unamed static array of chars
Right. When it is not an array initializer, it always produces
an anonymous array. This array has "static duration" -- meaning
it is valid during the entire execution of the program -- and may
or may not reside in physically-read-only storage. If it is
physically read-only, attempts to change it will fail:
char *p = "mellow";
*p = 'y';
may leave *p unchanged, and/or may trap at runtime. The effect is
formally undefined, and a compiler may well get confused and *think*
it changed even if it did not. It might even present you with
conflicting evidence, showing that it has both changed and not
changed:
printf("*p is '%c'; p is '%s'\n", *p, p);
might print:
*p is 'y'; p is 'mellow'
Here the compiler "knows" it just set *p to 'y', so it can replace
*p with 'y' in the call to printf(); but printf's %s format reads
what is really still there in read-only memory, which is an 'm'.
So my question its:
if i declare:
char *myString="What ever";
and later in the code:
myString="Anot her Static Array of chars";
the pointer value will be the same ?
No -- in this case, the two values stored in myString *must* be
distinct and compare not equal. More specifically, after:
char *p1 = "one such array";
char *p2 = "something different";
it must definitely be the case that p1 != p2. However, in:
char *p3 = "we will see this again";
char *p4 = "we will see this again";
the compiler is allowed, but not required, to use a single array
to hold both strings, so that p3==p4 and p3!=p4 are *both* allowed.
Aside from the fact that the anonymous array is (at least in
principle) read-only -- and of course anonymous (unnamed) -- these
four string literals are just shorthand for:
static char __compiler_stri ng_number_00000 1[] = "one such array";
static char __compiler_stri ng_number_00000 2[] = "something different";
static char __compiler_stri ng_number_00000 3[] = "we will see this again";
char *p1 = __compiler_stri ng_number_00000 1;
char *p2 = __compiler_stri ng_number_00000 2;
char *p3 = __compiler_stri ng_number_00000 3;
Whether p4 is __compiler_stri ng_number_00000 4 or
__compiler_stri ng_number_00000 3 again is up to the compiler. Asking
whether p3==p4 is the same, in this case, as asking whether
__compiler_stri ng_number_00000 3 was re-used.
It would make more sense if these were:
static const char __compiler_stri ng_number_00000 1[] = ...
but the 1989 C standard left the type unqualified (non-"const")
for backwards compatibility with all those C compilers that came
before it, where there was no "const" keyword.
Finally, in the original example, we had, in effect:
p1 = "some string that ends with a specific word";
followed by:
p2 = "specific word";
In this case, a compiler is allowed -- but again not required -- to
act more or less as if we had written:
static char __compiler_stri ng_number_00004 2[] =
"some string that ends with a specific word";
/* 1 2 3 4 */
/* 012345678901234 567890123456789 0123456789012 */
p1 = __compiler_stri ng_number_00004 2;
p2 = __compiler_stri ng_number_00004 2 + 29;
As you can see from the comment (assuming you are viewing this in
a fixed-width font), the text "specific word" occurs at offset 29
within the string "some string that ends with a specific word".
(This optimization turns out to be relatively easy to make -- one
just needs to collect all strings, group them by size, and then
"compare backwards" to see if any one string is an exact match for
the end of any equal-length-or-longer string. This does not catch
all possible matches due to the ability to embed '\0' characters
in a string literal, but the algorithm can be augmented if desired.
Note that counted-length strings, which are being discussed in a
separate ongoing thread in comp.lang.c now, do not lend themselves
as easily to this string-sharing technique. There are two main
ways to do counted-length strings, one of which prohibits sharing
entirely and the other of which affords even more opportunities for
sharing, so that a simple tail-match algorithm is insufficient.)
Another questions
If i:
char *MyString1="Dog "; char *MyString2="Cat ";
MyString1=Myst ring2;
What happens with the initial memory referenced by MyString1 (Dog), it remains on the memory (wasted memory) or it gets cleared in some way ?
It remains in memory, because a static-duration array exists until
the program exits (and maybe even after that; the C standard
necessarily says nothing about what happens before and after a
program runs).
As for whether this memory is "wasted", ask yourself this question:
if the memory containing the string were to be used for something
else, how would it (a) get set up initially, and (b) get "restored"
if the function in question were re-entered? For instance:
void f(void) {
char *s;
s = "hello";
puts(s);
s = "world";
puts(s);
}
void g(void) {
f();
f();
}
Each time f() is called, the strings "hello" and "world" must be
copied to stdout (and a newline added after each, as puts() does).
If the six bytes that hold {'h', 'e', 'l', 'l', 'o', '\0'} were
ever replaced with another six bytes, who or what would put back
the original h e l l o \0 sequence? Would that take code and/or
data space in the program? Would it take *more* code and/or data
space than you might save by overwriting the original string?
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
On Sat, 6 Mar 2004 14:00:34 -0600, Adrian de los Santos
<de*********@de mon.com.mx> wrote: On 2004-03-06 13:22:24 -0600, Tor Husabø <to***@student. hf.uio.no> said: char *str does not become a constant! It's "hello" that is "constant" (in the sense that modifying it is has undefined behavior, even if it might work on your implementation) .
This is allowed, however:
char other_string[] = "goodbye"; char *str="hello"; str = other_string;
now str points to "goodbye", and "hello" is just wasted memory, since you dont have the address anymore.
Oh yea i read the faq, thanks a lot for pointing me there..
So, as the faq says
- A string literal can be: - An array initializer - An unamed static array of chars
So my question its:
if i declare:
char *myString="What ever";
and later in the code:
myString="Anot her Static Array of chars";
the pointer value will be the same ?
i mean:
"Another Static Array of chars" will start on the same memory address than "Whatever" ?
Not at all. Both arrays exist in your program for the life of the
program. Therefore, they cannot occupy the same memory. At the
start, myString contains the address of (points to) the 'W'. After
the assignment, it contains the address of the 'A', which is
guaranteed to be different.
This is no different than
char array1[] = "Whatever";
char array2[] = "Another Static Array of chars";
char *myString = array1;
...
myString = array2;
Surely you don't think array1 and array2 occupy the same memory. Another questions
If i:
char *MyString1="Dog "; char *MyString2="Cat ";
MyString1=Myst ring2;
What happens with the initial memory referenced by MyString1 (Dog), it remains on the memory (wasted memory) or it gets cleared in some way ?
String literals survive for the life of the program.
The assignment does absolutely nothing to the objects being pointed
to. The only thing that changes is the contents (value) of MyString1.
It now has the same value as MyString2, namely the address of the 'C'.
Whether the four bytes occupied by "Dog" are wasted or not depends on
whether something else points to them or can point to them later.
Consider the following
char *MyString1="Dog ";
char *MyString2="Cat ";
char *newptr = MyString1;
...
MyString1 = MyString2;
You would be more than a little annoyed, and rightly so, if you
subsequently used newptr and did not get the value "Dog".
<<Remove the del for email>> This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Giampiero Gabbiani |
last post by:
Is it possible to reset a std::stringstream in order to reuse it once more?
I tried with flush() method without any success...
Thanks in advance
Giampiero
|
by: Charles M. Fish, Sr. |
last post by:
I’m so tired from banging this problem around all day, I hope I can
explain it succinctly & accurately.
I want to execute a function immediately following a click on <input
type="RESET"...
The function will insert today’s date into a <input type="TEXT"… field.
It does it just fine with <form onload="insertDate();" where inside the
‘insertDate’ fn, I have document.form.dateField.value = dateString. The
closest I’ve been able to do...
|
by: Ken Varn |
last post by:
Is there any way to reset a foreach loop to re-iterate through the
collection as if it were starting from the beginning? Namely, if I delete
an item out of a collection, I want to be able to reset the loop.
--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.
|
by: NancyASAP |
last post by:
Thought I'd share this since it took me a long time to get it working.
Thanks to a bunch of contributers in Google Groups who shared
javascript, etc.
The question was: How can I put a reset button on my ASP.NET web page,
and have an HTML reset button click clear 1) all validator text display
and 2) validation summary display. Problem was clearing them and yet
still leaving them working and visible if the user immediately began...
|
by: Lee Chapman |
last post by:
Hi,
Can anyone tell me why in the code below, the call to ClearChildViewState()
has no effect?
To paraphrase the code: I'm using view state. I have a textbox and a submit
button (and a label that can be ignored). When I press the button the first
time, the click handler hides the textbox. Pressing the button a second time
unhides the textbox. The text box is maintaining its value when hidden via
view state. (The value is NOT being...
| |
by: Nathan Sokalski |
last post by:
I have a user control that contains three variables which are accessed through public properties. They are declared immediately below the "Web Form Designer Generated Code" section. Every time an event is fired by one of the controls contained in the User Control, these variable are reset. Here is my current code (I have a little more to add later, right now I am just concerned about the variables getting reset):
Public Class DatePicker2...
|
by: Kermit Piper |
last post by:
Hello,
How can you clear session variables when a reset button is pressed? I
thought I might be able to do something like:
<%
If request.form("Reset") = "Reset" then
Session("variable") = Null
%>
|
by: wvtempl |
last post by:
From the documentation in MSDN, it looks as though the following should
iterate through the collection twice. However, MoveNext in the second
iteration returns false:
Dim oList As New List(Of String)
oList.Add("Hello")
oList.Add("world")
Dim oEnum As List(Of String).Enumerator = oList.GetEnumerator()
While oEnum.MoveNext()
Dim sValue As String = oEnum.Current
End While
|
by: RNEELY |
last post by:
I've inherited code similar to the following with a comment on resetting the
string. Why would anyone want to do this? How could this reset the string?
What does it mean to reset a string?
Public Sub SetTheStringToSomething(ByRef OutStr As String)
OutStr = "123"
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
|
by: jarice1978 |
last post by:
Hello,
I have been scanning the internet for a few days now. That is not working. So now it is time to post!
I have read a few other posts on here about authentication but they do not match exactly.
We currently have an intranet app built in a mixture of asp and asp.net 1.1 and 2.0 written in VB .Net. We have a form where the user logs in and it authenticates against active directory successully in 2 ways:
1. The admin resets the...
|
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,...
| |
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...
|
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |