Why does this not work:
SomeClass::SomeClass(char *lit) //Ctor
{
str = new char[strlen(lit)+1]; // str is a pointer to char in SomeClass
strcpy(str,"have");
cout << str << " " << "In Ctor" << " +Size=" << strlen(str)<< endl;
}
The above code shows a string with length 0. But this code works:
SomeClass::SomeClass(char *lit)
{
char newstr[strlen(lit)+1];
strcpy(newstr,"have");
cout << newstr << " " << "In Ctor" << " +Size=" << strlen(newstr)<< endl;
}
Here is the complete code.
EDIT:
Added the link to Ideone which OP removed after I answered the Question.
Without the link to source code, this Q & answer to it is useless.
There is no problem with the strcpy, You are just messing your pointer.
The problem is here:
str = new char[strlen(lit)+1];
strcpy(str,lit);
length=leng(); <------------- str points to \0 after this call
cout << str << " " << "In Ctor" << " +Size=" << strlen(lit)<< endl;
str is your class member and You move the pointer str to point to the \0 in the function leng(), Naturally, You don't see any output in the next statement.
Solution is to hold the starting address in a separate pointer inside the function.
int String :: leng()
{
int length=0;
char *tempPtr= str; <----------- Store the address in a temporary pointer
while(*str)
{
length++;
str++;
}
str = tempPtr; <---------- Point the Pointer member to right address again
return length;
}
Another way to write String::leng():
int String::leng()
{
char *endPtr = str;
while(*endPtr)
endPtr++;
return endPtr - str;
}
Related
Take this question when i read a program (quote:c++ primer plus) 4.22 and make some change in it
#include <iostream>
#include <cstring>
using namespace std;
char * getName();
int main(int argc, const char * argv[]) {
// insert code here...
char *name;
name = getName();
string sb = name;
cout << name << " at " << (int *)name << "\n";
cout << *name << " " << sb << endl;
cout << &sb << endl;
delete [] name;
name = getName();
sb = name;
cout << name << " at " << (int *) name << "\n";
cout << *name << " " << sb << endl;
cout << &sb << endl;
delete [] name;
cout << sb << endl;
cout << &sb << endl;
return 0;
}
char *getName()
{
char temp[80];
cout << "Enter last name: ";
cin >> temp;
char *pn = new char[strlen(temp) + 1];
strcpy(pn, temp);
return pn;
}
and there have no memory leak.
i check sb's address is different from name.
i think may it work like this
std::string
first step : malloc (char *, sizeof(char *) * sizeof(name) )
then : snprintf( string , sizeof (string) , "%s", name)
final : string get a new address
if i use a statement:
string = string + " am i a pointer";
it still work.
i guess it is really a pointer!
just realloc it
hereby, i think string is kind of char* or char array, i try to *string then the compiler tell me something wrong with it! i can't use like this, so i hope someone can explain what type of string is in compiler and how it work! why string is not a pointer? or it's actually a pointer but it have special method to use?
tip:All work on mac os
i hope someone can explain what type of string is
It is a class.
why string is not a pointer? or it's actually a pointer but it have special method to use?
It's not a pointer. A pointer couldn't store the necessary data to fulfill the requirements defined by the standard.
i think string is kind of char* or char array
It's not. However, it quite probably does have a char pointer to an array as a data member.
Why doesn't the address change as I increment str? I thought that when I performed pointer arithmetic, the pointer points to a different memory address. Therefore, shouldn't the memory address change as well?
#include <iostream>
using namespace std;
void reverse(char* str){
cout << &str << endl;
while(*str != '\0'){
cout << &str << endl;
str++;
}
}
int main(){
char str[] = "hello";
reverse(str);
}
&str is the address of the pointer. You are changing the pointer as you iterate over the characters, but the pointer that you are changing is still located at the same spot.
Edit: change your cout << &str << endl; to cout << "pointer loc<" << &str << "> pointer value<" << (void*)str << ">" << endl; and see what it says.
I have a program with one structnamed sample, it contains 2 int members and one char *. when creating 2 objects called a and b, I try assign a new dynamic string to a with the pointer and then copy all the values to b. so b = a. But later on when try to make changes to a like this : a.ptr[1] = 'X'; the pointer in b also changes. I want to know why, and how can I solve this.
struct Sample{
int one;
int two;
char* sPtr = nullptr;
};
int _tmain(int argc, _TCHAR* argv[])
{
Sample a;
Sample b;
char *s = "Hello, World";
a.sPtr = new char[strlen(s) + 1];
strcpy_s(a.sPtr, strlen(s) + 1, s);
a.one = 1;
a.two = 2;
b.one = b.two = 9999;
b = a;
cout << "After assigning a to b:" << endl;
cout << "b=(" << b.one << "," << b.two << "," << b.sPtr << ")" << endl << endl;
a.sPtr[1] = 'X' ;
cout << "After changing sPtr[1] with 'x', b also changed value : " << endl;
cout << "a=(" << a.one << "," << a.two << "," << a.sPtr << ")" << endl;
cout << "b=(" << b.one << "," << b.two << "," << b.sPtr << ")" << endl;
cout << endl << "testing adresses for a and b: " << &a.sPtr << " & b is: " << &b.sPtr << endl;
return 0;
}
Your struct contains a char*. When you assign all values in a to b, the pointer is also copied.
This means that a and b now point to the same char array. Therefore changing a value in this char array changes it for both structs.
If you do not want this, make a new char array for b and use strcpy.
You are copying the pointer not the value. To solve this you could override your assignment operator in the structure:
struct Sample{
int one;
int two;
char* sPtr = nullptr;
Sample& operator=(const Sample& inputSample)
{
one = inputSample.one;
two = inputSample.two;
sPtr = new char[strlen(inputSample.sPtr) + 1];
strcpy (sPtr, inputSample.sPtr);
return *this;
}
};
I'm bit puzzled by how modifying a std::string beyond its size is handled? In an example I tried, it allowed me to modify the string beyond its size using op[] (and I'm aware that standard doesn't stop you from doing it). However, when I print the string using cout it prints the original string but when I print whats returned by cstr (), it prints the modified version. How does it keep track of both sizes (3 & 5)?.
#include <string>
#include <iostream>
using namespace std;
int main(void) {
std::string a = "abc";
cout << "str before : " << a << endl;
const char * charPtr = a.c_str ();
cout << "c_str before : " << charPtr << endl;
cout << "str size / capacity : " << a.size () << ", " << a.capacity () << endl;
a[3] = 'd';
a[4] = 'e';
cout << "str after : " << a << endl;
const char * charPtr2 = a.c_str ();
cout << "c_str after : " << charPtr2 << endl;
cout << "str size / capacity : " << a.size () << ", " << a.capacity () << endl;
return 0;
}
output :
str before : abc
c_str before : abc
str size / capacity : 3, 3
str after : abc
c_str after : abcde
str size / capacity : 3, 3
Although you already got a correct comment saying the behaviour is undefined, there is something worthy of an actual answer too.
A C++ string object can contain any sequence of characters you like. A C-style string is terminated by the first '\0'. Consequently, a C++ string object must store the size somewhere other than by searching for the '\0': it may contain embedded '\0' characters.
#include <string>
#include <iostream>
int main() {
std::string s = "abc";
s += '\0';
s += "def";
std::cout << s << std::endl;
std::cout << s.c_str() << std::endl;
}
Running this, and piping the output through cat -v to make control characters visible, I see:
abc^#def
abc
This explains what you're seeing: you're overwriting the '\0' terminator, but you're not overwriting the size, which is stored separately.
As pointed out by kec, you might have seen garbage except you were lucky enough to have an additional zero byte after your extra characters.
I have a function that takes two strings and determines if they are the same. I am trying to tokenize the string and combine all of tokens into one string. This is what I have so far and I am getting Bus error :10.
any help appreciated.
#include <iostream>
#include <string>
using namespace std;
bool stringCheck(string s1, string s2){
string strCheck1 = "";
string strCheck2 = "";
char *cstr1 = new char[s1.length()]; // char array with length of string
strcpy(cstr1, s1.c_str()); // copies characters of string to char array
char *cstr2 = new char[s2.length()];
strcpy(cstr2, s2.c_str());
char *p1 = strtok(cstr1, " "); // creates a char array that stores token that
// is delimeted
cout << "p1 " << p1 << endl; ///outputs token that is found
strCheck1.append(p1); // appends token to string
cout << "strCheck1 " << strCheck1 << endl; // outputs string
while(p1 != NULL) // while the token is not a null character
{
cout<<"parsing" << endl;
p1 = strtok(NULL, " "); // continue to parse current string.
cout << "p1 " << p1 << endl;
strCheck1.append(p1);
cout << "str1 " << strCheck1 << endl;
}
char * p2 = strtok(cstr2, " ");
cout << "p2 " << p2 << endl;
strCheck2.append(p2);
cout << "strCheck2 " << strCheck2 << endl;
while(p2 != null){
p2 = strtok(NULL, " ");
strCheck2.append(p2);
cout << "str2 " << strCheck2 << endl;
}
if( strCheck1.compare(strCheck2) != 0)
{
return 0;
}
else return 1;
}
int main(void){
string s1 = "jam yoooo jay";
string s2 = "jam yoooo";
if(stringCheck(s1, s2) == 1){
cout << "strings same"<< endl;;
}
else{
cout << "strings not same" << endl;
}
}
is there a conditional statement I could pair up with
while(p1 != NULL)
I know this is a pretty silly function but just trying to polish up my skills. any help appreciated!
There are some things you must change:
char *cstr1 = new char[s1.length()];
c-string are null-terminated, so you need one more char to store the null character:
char *cstr1 = new char[s1.length() + 1];
(same for cstr2)
strCheck1.append(p1)
p1 cannot be a null pointer (see Assign a nullptr to a std::string is safe? for further details). So you have to check...
if (p1) strCheck1.append(p1);
(same for p2).
cout << p1 << endl
if p1 is a null pointer bad things can happen (see Why does std::cout output disappear completely after NULL is sent to it). So you have to check...
if (p1) { cout << "p1 " << p1 << endl; strCheck1.append(p1); }
(same for p2)
there is a memory leak (cstr1 / cstr2 must be deleted).
At the end it should work.
Probably you should consider other systems to extract tokens (where you haven't to mix std::string and c-string). E.g.:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string text("text-to-tokenize");
std::istringstream iss(text);
std::string token;
while(getline(iss, token, '-'))
std::cout << token << std::endl;
return 0;
}