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

Home Posts Topics Members FAQ

string copy

bml
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!
Nov 14 '05 #1
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
Nov 14 '05 #2
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
Nov 14 '05 #3
"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);
Nov 14 '05 #4
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..

Nov 14 '05 #5
bml wrote:
char s1 = "this string";
const char * s1 = "this string";
Always treat string literals as constants. Thus
s1 is declared as a pointer to constant data.
Constant meaning it won't change.

char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);
char * s2;
if (strlen(s1) < 30)
{
s2 = malloc(30);
}
else
{
s2 = malloc(strlen(s 1) + 1);
}
if (s2 == NULL)
{
/* error processing */
}


/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');
strcpy(s2, s1); /* copy string s1 to s2 */


/* Why empty content of s2 print out here*/
puts("String s2:");
puts(s2);

Thanks a lot!


--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Nov 14 '05 #6
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/
Nov 14 '05 #7


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/

Nov 14 '05 #8
"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 ;-)
Nov 14 '05 #9
"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?
Nov 14 '05 #10

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

Similar topics

22
13297
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;
16
16416
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
4
8814
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...
19
78821
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.
12
6649
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
32
2370
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
12
7203
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?
5
7232
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)'
6
5667
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...
6
5710
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.
0
8678
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
8609
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
9030
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...
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
8871
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
7737
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...
0
4621
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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
2333
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.