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.
Related
I have this header:
MvProjectQueue & operator >> (char *);
And I have to write a function meeting this spec. (my function should "return" an array of chars using >> operator)
I have to change the passed argument, i.e. I get an array of char when my function is called and I have to modify it (in place).
Normally I would use
MvProjectQueue & operator >> (char **);
got a pointer to char * and I would solved it easily, using something like this:
#include <iostream>
using namespace std;
class SimpleShowcaseObject
{
public:
SimpleShowcaseObject(){};
~SimpleShowcaseObject(){};
SimpleShowcaseObject & operator >> (char ** p_ch)
{
*p_ch = "changed";
cout << "in scope: " << *p_ch << endl;
return *this;
}
};
int main(void)
{
char *ch = new char[10];
ch = "hello";
SimpleShowcaseObject o = SimpleShowcaseObject();
cout << "original: " << ch << endl;
o >> &ch;
cout <<"changed: " << ch << endl;
delete[] ch;
cin.get();
return 0;
}
But this:
#include <iostream>
using namespace std;
class SimpleShowcaseObject
{
public:
SimpleShowcaseObject(){};
~SimpleShowcaseObject(){};
SimpleShowcaseObject & operator >> (char *ch)
{
ch = "changed";
cout << "in scope: " << ch << endl;
return *this;
}
};
int main(void)
{
char *ch = new char[10];
ch = "hello";
SimpleShowcaseObject o = SimpleShowcaseObject();
cout << "original: " << ch << endl;
o >> ch;
cout <<"changed: " << ch << endl;
delete[] ch;
cin.get();
return 0;
}
executes and prints:
original: hello
in scope: changed
changed: hello
and I would like to have
original: hello
in scope: changed
changed: changed
(edited several times, big thanks to everyone for trying to help!)
Your function receive what should be a buffer you can write to:
SimpleShowcaseObject & operator >> (char *ch)
{
//ch = "changed";// with this you are changing the value of the pointer, not what you want
strcpy (ch, "changed");
cout << "in scope: " << ch << endl;
return *this;
}
As other have already pointed out, this is not a good design: your operator >> has to write a string (char[]) in a buffer, without knowing the lenght of input buffer; not a nice scenario.
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.
For the life of me I can't figure out why the I can't write to a c style string inside of a struct.
College student - can't use string class, haven't learned pointers.
Help? 2 hours at trying to figure this out.
#include <iostream>
using namespace std;
void strCopy(char from[], char to[])
{
for (int i = 0; i < 255; i++)
{
to[i] = from[i];
}
}
struct card
{
char suit[20];
char rank[20];
int cvalue;
char location[20];
};
void printCard(card card)
{
cout << card.rank << " of " << card.suit << endl;
}
int main()
{
// I don't think strCopy()'s the problem, I've used it with my last project.
cout << "Test strCopy()" << endl;
char str1[14] = "abcdefghijklm";
char str2[14];
strCopy(str1, str2);
cout << " " << str2 << endl << endl;
// Now the negative.
card one;
one.cvalue = 2;
strCopy("Somewhere", one.location);
strCopy("Two", one.rank);
strCopy("Hearts", one.suit);
printCard(one);
}
// I don't think strCopy()'s the problem, I've used it with my last
project.
Wrong
for (int i = 0; i < 255; i++)
{
to[i] = from[i];
}
copies 255 characters, however that's not what you meant.
If here :
strCopy(str1, str2);
cout << " " << str2 << endl << endl;
Your're getting "correct" output, then you're just unlucky, since that invokes an undefined behavior, an you're writing off the end of the array.
I have implemented the swap via function for two numbers and this works well. However, I am now trying to swap two character strings but i receive the names in the same order. Would anybody know where I am going wrong or what I could do to have the names change positions? here is an example of the code below:
#include "stdafx.h"
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
void swapages (int &age1, int &age2);
void swapname(char *person1, char *person2);
int _tmain(int argc, _TCHAR*argv[])
{
char person1[] = "Alex";
char person2[] = "Toby";
int age1 = 22;
int age2 = 27;
cout << endl << "Person1 is called " << person1;
cout << " and is " << age1 << " years old." << endl;
cout << "Person2 is called " << person2;
cout << " and is " << age2 << " years old." << endl;
swapname(person1,person2);
swapages(age1,age2);
cout << endl << "Swap names..." << endl;
cout << endl << "Person1 is now called " << person1;
cout << " and is " << age1 << " years old." << endl;
cout << "Person2 is now called " << person2;
cout << " and is " << age2 << " years old." << endl;
system("pause");
return 0;
}
void swapages(int &age1, int &age2)
{
int tmp = age2;
age2 = age1;
age1 = tmp;
}
void swapname(char *person1, char *person2)
{
char* temp = person2;
person2 = person1;
person1 = temp;
}
You have tagged this as C++, and you are including the <string> header already, so why not use std:string instead of all those pointers and arrays?
void swapname(string &person1, string &person2)
{
string temp(person2);
person2 = person1;
person1 = temp;
}
int _tmain(int argc, _TCHAR*argv[])
{
string person1 = "Alex";
string person2 = "Toby";
swapname(person1, person2);
}
The problem is that you are trying to swap pointers that are local variables of the function while you need to swap strings. So you need to copy one string into another string. Moreover the strings can have different lengths so the exact swap will be impossible. It could be done without problems if the parameters of the function would be arrays (references to arrays) of the same size. For example
void swap_name( char ( &lhs )[5], char ( &rhs )[5] )
{
char tmp[5];
std::strcpy( tmp, lhs );
std::strcpy( lhs, rhs );
std::strcpy( rhs, tmp );
}
You need to make minor changes to get it to work the way you want it to work.
void swapname(char **person1, char **person2);
.
.
char *person1 = "Alex";
char *person2 = "Toby";
.
.
swapname(&person1, &person2);
.
.
and
void swapname(char **person1, char **person2)
{
char* temp = *person2;
*person2 = *person1;
*person1 = temp;
}
In your code, person1 and person2 are defined as 2 char arrays not char pointer variables, you can not swap them, if you pass the 2 arrays into the swapname function which takes 2 pointers as parameters, it should not even compile.
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;
}