473,795 Members | 2,443 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

copy char*


string a = "abcdef";
aa[80] = a.c_str();

bb[40] = how can I get def from aa in here?

thanks
Nov 15 '06
20 5101
Gary Wessle wrote:
string a = "abcdef";
aa[80] = a.c_str();
This is an error: you can't assign to arrays
bb[40] = how can I get def from aa in here?
Assuming you have managed to get "a" into "aa" successfully:
memcpy(bb, aa + 3, 3);

Nov 16 '06 #11
I need it to ouput
abc def

what must be done to
strncpy(_frst, pair, 3);
strncpy(_second , pair+4, 3);
in the c'tor?
Nov 16 '06 #12

Default User wrote in message <4s************ @mid.individual .net>...
>BobR wrote:
<snip **incomplete** func1>
>// out: frst=abc last=def

Did you actually try this?
Yes.
If you got the purported results, then it
was by sheer bad luck. You didn't terminate the string, and strncpy
doesn't do it for you. Outputting the result was undefined behavior.
Of course you are correct. My bad. (gads, I hate that phrase!!).
Thanks for the 'heads-up'.

<?>
It must have been that the char arrays were initialized to zeros by my
compiler.
<checking.... >
Nope!!! Just happened to be a zero at 4th position in both arrays.
[....even on re-compiles. ....and adding another array before those.]
[ I can't seem to break it! ]
</?>

Murphy's "bad luck" clause strikes again!!

Thanks again for the correction.
--
Bob R
POVrookie
Nov 16 '06 #13

Default User wrote in message <4s************ @mid.individual .net>...
>BobR wrote:

Outputting the result was undefined behavior.
[ ref: the missing terminator. ]

HEY! How come why for you yell at me but not Jim?
<G>

--
Bob R
POVrookie
Nov 16 '06 #14
in order to get the clean output "abd def" I did some changes to the
code but now getting Seg Fault.

#include <string>
#include <iostream>
using namespace std;

class myType {
protected:
char _frst[40];
char _second[40];
char _pair[80];
public:
const char* frst() const;
const char* second() const;
myType(const char* pair);
};

myType::myType( const char* pair)
{
strncpy(_frst, pair, 3);
strncpy(_second , pair+4, 3);
}
const char* myType::frst()c onst {
char* r;
strncpy(r,_frst ,3);
return r;}
const char* myType::second( )const {
char* r;
strncpy(r,_seco nd,3);
return r;
}

int main(){
string s = "abc-def";
myType mt(s.c_str());
cout << mt.frst() << " " << mt.second() << endl;
}
Nov 16 '06 #15

Gary Wessle wrote in message ...
>
#include <string>
#include <iostream>
using namespace std;

class myType { protected:
char _frst[40];
char _second[40];
char _pair[80];
public:
const char* frst() const;
const char* second() const;
myType(const char* pair);
};

myType::myType (const char* pair){
strncpy(_frst, pair, 3);
// Like Default User pointed out, I forgot to terminate the array:
_frst[4] = '\0';
strncpy(_second , pair+4, 3);
_second[4] = '\0';

// or:
// frst[4]= 0;
// second[4]= 0;

// also, BAD nameing.
// Put the underscore on the end (not the begin) of the names
// if you MUST use them.
>}
const char* myType::frst()c onst {return _frst;}
const char* myType::second( )const {return _second;}

int main(){
string s = "abc-def";
// You changed the spec on us!
// I'll let you figure out the 'fix' as punishment.
myType mt(s.c_str());
string tmp = mt.frst();
string tmp2 = mt.second();
cout << tmp << " " << tmp2 << endl;
}

//output
abcMh
Q%G.ANoN?N =NoN?N=NoN ?N=NoN?N=% @`%G.ANoN? N=%@M$B'\(B $
B%G.ANoN?N= (B$B%@(B def

You were luckier than I was!! <G>

--
Bob R
POVrookie

Nov 16 '06 #16

Gary Wessle wrote in message ...
>in order to get the clean output "abd def" I did some changes to the
code but now getting Seg Fault.

#include <string>
#include <iostream>
using namespace std;

class myType {
protected:
char _frst[40];
char _second[40];
char _pair[80];
public:
const char* frst() const;
const char* second() const;
myType(const char* pair);
};

myType::myType (const char* pair){
strncpy(_frst, pair, 3);
_frst[ 4 ] = 0;
strncpy(_second , pair+4, 3);
_second[ 4 ] = 0;
>}
>const char* myType::frst()c onst {
char* r;
OK, when working with raw arrays, you always need to ask yourself, "Is there
enough room in there?".
You declared 'r' as a pointer to type 'char', but, where is the storage for
the 'strncpy' to copy to? You need to make some storage, and then put the
address of that into 'r'.
You are getting the 'Seg Fault' because you did not point 'r' to anything, or
initialize it. It's pointing to something that is not yours to change.

Now before you get the idea to do:

char *r( new char[ 40 ] );

....remember that now you are putting the life of that pointed to storage in
the callers hands, it's up to them to see that it is eventually
'delete[]'ed!!
Hint: 'cout' don't know how to fo that!
The easy fix is to dump the 'strncpy' and 'char*' here, and just do:

return _frst;
// strncpy(r,_frst ,3);
// return r;
}
>const char* myType::second( )const {
char* r;
Same here.
strncpy(r,_seco nd,3);
return r;
}

int main(){
string s = "abc-def";
myType mt(s.c_str());
cout << mt.frst() << " " << mt.second() << endl;
}
Alf P. Steinbach's "Pointers" document:
http://home.no.net/dubjai/win32cpptu...ters/ch_01.pdf

--
Bob R
POVrookie
--
Get "Thinking in C++", 2nd ed. Volume 1(&2) by Bruce Eckel
(available for free here. You can buy it in hardcopy too.):
http://www.mindview.net/Books/TICPP/...ngInCPP2e.html
Nov 16 '06 #17
"BobR" <Re***********@ worldnet.att.ne twrote in message
news:m0******** ************@bg tnsc04-news.ops.worldn et.att.net...
>
Default User wrote in message <4s************ @mid.individual .net>...
>>BobR wrote:

Outputting the result was undefined behavior.

[ ref: the missing terminator. ]

HEY! How come why for you yell at me but not Jim?
<G>
Because I didn't try to output the result. I just gave the op what he asked
for, abc in the first, cdf in the second. He didn't ask to terminate them,
nor even why he was doing it. Now, if he actually wants to output them, I
would do it a different way. I suggested he use std::string anyway.
Nov 16 '06 #18

Jim Langston wrote in message ...
>"BobR" wrote in message...
>>
Default User wrote in message ...
>>>
Outputting the result was undefined behavior.

[ ref: the missing terminator. ]

HEY! How come why for you yell at me but not Jim?
<G>

Because I didn't try to output the result.
Yeah, <pointing at headI gots no kidneys!!
I suggested he use std::string anyway.
Must be some 'learning' thing, std::string would be too easy.

--
Bob R
POVrookie
Nov 16 '06 #19
Old Wolf wrote:
Gary Wessle wrote:
string a = "abcdef";
aa[80] = a.c_str();

This is an error: you can't assign to arrays
But you can to an array element, which is why his missing declarations
for things like aa made the problem insoluable.

If aa were declared something like:

const char *aa[81];

Then you could assign the results from c_str() to that element. Now,
that's apparently not what he was going for.


Brian
Nov 16 '06 #20

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

Similar topics

4
7174
by: franky.backeljauw | last post by:
Hello, I have a problem with using a copy constructor to convert an object of a templated class to object of another templated class. Let me first include the code (my question is below): <code:templates.h> #include <string> #include <iostream>
6
9494
by: Charles Herman | last post by:
I am using push_back to place a class object into a vector. This class contains data members that are pointers to a char string. When I use push_back, I believe a copy of the object is first made, and then deposited into the vector. But I want this copy to not mereley copy the pointer to the char string, but rather, I want to malloc new space, and make a copy of the char string. The default copy constructor is defined as
22
2865
by: Shea Martin | last post by:
I have a String class (I know I am re-inventing the wheel, yes I have heard of boost, and of QString). My copy constructor does a deep (strcpy) of the char *_buffer member. I have a member function func(const String &param). When an actual String is passed as the param this is nice and efficient. I have a constructor which takes a const char* as an argument. And
1
2227
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen pertaining to casting class A to class B, the implementation of the
4
8828
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...
11
1821
by: csudha | last post by:
Hi all, Can you please explain me the usage of copy constructor and how do we use it. Give me some example. Regards, Sudha.
6
1543
by: Gary | last post by:
I'm confused about the two ways of string copy below. The first one (two functions) works; the second doesn't. Can anybody explain the reason to me? Thanks a lot. #include <stdio.h> /*this one works well void copy (char *s, char *t) { int i = 0;
5
2444
by: sarathy | last post by:
Hi, I need to see the output of the program when no copy constructor is used. Since by default, there is an implicit one, how should i perform the override, so as to totally remove the copy constructor functionality. Consider the following code. class Employee {
11
3438
by: Nindi73 | last post by:
A few days a ago I posted my code for a deep copy pointer which doesn't require the pointee object to have a virtual copy constructor. I need help with checking that it was exception safe and exception neutral/ I got a reply from Bux with his code for a smart pointer with far fewer lines of code and more cleaner design, not over engineered like mine. ...
20
432
by: royashish | last post by:
Hi all , A question to the C++ fraternity , Why the Copy constructor ? Was suggested in Effective C++ , In Case the Object contains a Char* , a assignment operator = makes the two object point to the same address . In this case any Of the two Object is destroyed a memory leak occurs as one of the object stays on the Heap . My experiments on the same have proved otherwise .
0
9672
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
9519
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
10438
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...
0
10001
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
9042
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
7540
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
5437
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...
1
4113
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
3
2920
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.