char s1 = "this string";
char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);
/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');
/* Why empty content of s2 print out here*/
Thanks a lot! 13 11450
bml wrote: char s1 = "this string";
char *s2; s2 = (char *)malloc(30); memset(s2, 0, 30);
/* this supposes to copy string s1 to s2 */ while((*s2++ = *s1++) != '\0');
/* Why empty content of s2 print out here*/
Hint: What is s2 now pointing to?
[BTW -- in the future, post *real* code (the most minimal possible
runnable snippet); otherwise we're just guessing.]
HTH,
--ag
--
Artie Gold -- Austin, Texas
bml wrote: char s1 = "this string";
^^ missing '*' char *s2; s2 = (char *)malloc(30);
^^^^^^^ silly cast
No error check memset(s2, 0, 30);
^^^^^^^^^^^^^^^ ^^
useless function call /* this supposes to copy string s1 to s2 */ while((*s2++ = *s1++) != '\0');
/* Why empty content of s2 print out here*/
You were unlucky; your computer should have exploded.
Because s2 points beyond the end of the string. What did you think was
happening when you incremented it? Thanks a lot!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *s1 = "this string";
char *t1 = s1;
char *s2;
char *t2;
if (!(s2 = malloc(strlen(s 1) + 1))) {
fprintf(stderr, "malloc failed for s1\n");
exit(EXIT_FAILU RE);
}
t2 = s2;
while ((*t2++ = *t1++)) ;
printf("s1: \"%s\"\ns2: \"%s\"\n", s1, s2);
return 0;
}
--
Martin Ambuhl
"bml" <le*****@yahoo. com> writes: char s1 = "this string";
I assume this is a typo and you meant to write
char *s1 = "this string";
char *s2; s2 = (char *)malloc(30);
Don't cast malloc. It is not necessarry and may hide a serious error
if you forget to include <stdlib.h> (which provide the prototype for
malloc).
memset(s2, 0, 30);
Make sure malloc succeeded before accessing s2.
if (s2 != NULL)
/* use s2 here */
If you simply want to "empty" the string then *s2 = '\0' will do.
/* this supposes to copy string s1 to s2 */ while((*s2++ = *s1++) != '\0');
Why not simply use strcpy?
/* Why empty content of s2 print out here*/
Where does s2 point after the loop completes? You'll need to remember
the original pointer,
char *t = s2;
while (*s2++ = *s1++);
s2 = t;
printf ("%s\n", s2);
On 1 Feb 2004, Thomas Pfaff wrote: Where does s2 point after the loop completes? You'll need to remember the original pointer,
char *t = s2; while (*s2++ = *s1++); s2 = t;
char *t = s2;
while (*t++ = *s1++) ;
If this seems like a mindless nit I'm probably just overly biased against
the idiom of modifying a variable and then popping it back..
In 'comp.lang.c', "bml" <le*****@yahoo. com> wrote: char s1 = "this string";
char *s2; s2 = (char *)malloc(30); memset(s2, 0, 30);
/* this supposes to copy string s1 to s2 */ while((*s2++ = *s1++) != '\0');
/* Why empty content of s2 print out here*/
Empty ? I'm not sure. I would have said 'undeterminated ', due to the lack of
final 0.
add :
*s2 = 0;
but you are making a design mistake. You have changed the value of s2, hence
you have lost it's initial value:
- The string copy was somehow correct, but you don't know any more where does
the copied string begin.
- You are now unable to free the allocated block which has created a memory
leak. (A Bad Thing (c))
If you want to make a copy of a string, I recommend to desing your own
'strdup()' function:
#include <string.h>
#include <stdlib.h>
char *str_dup (char const * const s)
{
char *sdup;
if (s != NULL)
{
size_t size = strlen (s) + 1;
sdup = malloc (size);
if (sdup != NULL)
{
memcpy (sdup, s, size);
}
}
return sdup;
}
--
-ed- em**********@no os.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Emmanuel Delahaye wrote: If you want to make a copy of a string, I recommend to desing your own 'strdup()' function:
#include <string.h> #include <stdlib.h>
char *str_dup (char const * const s) { char *sdup;
To correct the flaw in the return value should the argument, s,
be a NULL value, make this:
char *sdup = NULL; if (s != NULL) { size_t size = strlen (s) + 1;
sdup = malloc (size);
if (sdup != NULL) { memcpy (sdup, s, size); } } return sdup; }
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email) http://www.geocities.com/abowers822/
"Emmanuel Delahaye" <em**********@n oos.fr> wrote in message
news:Xn******** *************** ****@213.228.0. 196... In 'comp.lang.c', "bml" <le*****@yahoo. com> wrote:
char s1 = "this string";
char *s2; s2 = (char *)malloc(30); memset(s2, 0, 30);
/* this supposes to copy string s1 to s2 */ while((*s2++ = *s1++) != '\0');
/* Why empty content of s2 print out here*/ Empty ? I'm not sure. I would have said 'undeterminated ', due to the lack
of final 0.
That's probably why he added the otherwise useless memset() in the first
place ;-)
"Thomas Matthews" <Th************ *************@s bcglobal.net> wrote in
message news:40******** ******@sbcgloba l.net... char * s2; if (strlen(s1) < 30) { s2 = malloc(30); } else { s2 = malloc(strlen(s 1) + 1); }
Why do you need the first branch? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jason Heyes |
last post by:
Does this function need to call eof after the while-loop to be correct?
bool read_file(std::string name, std::string &s)
{
std::ifstream in(name.c_str());
if (!in.is_open())
return false;
char c;
std::string str;
|
by: Khuong Dinh Pham |
last post by:
I have the contents of an image of type std::string. How can I make a
CxImage object with this type.
The parameters to CxImage is:
CxImage(byte* data, DWORD size)
Thx in advance
|
by: Simon Schaap |
last post by:
Hello,
I have encountered a strange problem and I hope you can help me to
understand it. What I want to do is to pass an array of chars to a
function that will split it up (on every location where a * occurs in
the string). This split function should allocate a 2D array of chars
and put the split results in different rows. The listing below shows
how I started to work on this. To keep the program simple and help
focus the program the...
|
by: Paul |
last post by:
hi, there,
for example,
char *mystr="##this is##a examp#le";
I want to replace all the "##" in mystr with "****". How can I do this?
I checked all the string functions in C, but did not find one.
|
by: Dave Bailey |
last post by:
I need to store an encrypted connection string in the
web.config file. I have found several examples on the Net
but nothing specific as to how to accomplish task.
Thanks in advance,
Dave
| |
by: Tubs |
last post by:
Am i missing something or does the .Net Framework have a quirk in the
way methods work on an object. In C++ MFC, if i have a CString and i
use the format method, i format the string i am using. In dotnet it
always asks me to pass it the string. Why can't i just say
"stringvariable.Format("0.00") and have it know what i mean. Is there
a way to achieve this? What am i doing wrong
|
by: CMirandaman |
last post by:
Sounds like a stupid question I know. I can tell that they are used to copy
strings. But what is the difference between
x = y;
versus x = String.Copy(y);
Or are they essentially the same?
|
by: Martin Jørgensen |
last post by:
Hello again,
Sorry to bother but I guess my C++ book isn't very good since it
obviously contains errors so the program code doesn't work with g++.
However I don't understand what the problem is. Last time the problem
was that "using namespace std" apparently had a "link" class/object
defined already. Now I get:
error: no matching function for call to 'String::String(String)'
|
by: Erik |
last post by:
Hello,
For many years ago I implemented my own string buffer class, which
works fine except assignments - it copies the char* buffer instead of
the pointer. Therefore in function calls I pass "const char*" and get
the result in a parameter by reference "MyString& result".
I'd like to move to nicer strings. In order to keep platform/compiler
independence I consider std:string as the replacement. While googling
I managed to read some...
|
by: arnuld |
last post by:
This works fine, I welcome any views/advices/coding-practices :)
/* C++ Primer - 4/e
*
* Exercise 8.9
* STATEMENT:
* write a program to store each line from a file into a
* vector<string>. Now, use istringstream to read read each line
* from the vector a word at a time.
|
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...
| |
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: 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...
|
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,...
|
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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |