Can't manage to use char pointers

Hi,

I am new to C++. I'm trying to create a string class for homework. Interface was given to me. I only need to code implemetation. But I couldn't figure out how to use char pointers. Here is my constructor. I am just trying to see outputs here.


1
2
3
4
5
6
7
  MyString::MyString(const char* s, int string_length){
    str = new char();
    *str = *s;
    cout << s << endl;
    cout << str << endl;
    length = string_length;
 }


And my Main:

1
2
3
4
5
6
int main()
{
    char *ss = "asdasd";
    MyString ms(ss, 6);
    return 0;
}


First cout works as expected. Prints out: "asdasd" .But the second one writes compeletely different things to screen. Why is it acting like this? What is wrong here? Second one probably writing its address to screen. But why?
Last edited on
Please, explain your lines 2 and 3 (of the constructor). What do they supposedly do?


(It would be nice to see the given interface. The main() has no MyString objects.)
new char() creates a single char.

*str = *s; assigns the char pointed to by s (the first char in the string) to the char pointed to by str (the char that you created on the previous line).

The << operator expects char pointers to point to the first character in a a char array and that the end of the string is marked using the null termination character '\0'. This is not the case in your problem. It will print *str and then continue printing the bytes in memory until it finds a null character (zero byte). This could cause a crash and/or garbage to be printed to the screen, or something else to happen.
Last edited on
I edited Main(). Sorry.

Thanks Peter87. I now understand the problem.

So how can I copy the value inside s variable to str ?? How can I make str exactly like s ? And do I need new char() ?
Reiz wrote:
How can I make str exactly like s ?
str = s;
I don't know if that's what you want though.
Last edited on
I figured it out:

1
2
3
4
5
6
MyString::MyString(const char* s, int string_length){
    str = new char[string_length]();
    for(int i = 0; i < string_length; i++)
            str[i] = s[i];
    length = string_length;
 }
Pointer is a variable that holds one value. A number. The number means a memory address.

In const char * gaz = "fubar"; the gaz stores the address of the 'f'.
The 'f' is actually in read-only memory, and the following five consecutive memory locations do hold values 'u', 'b', 'a', 'r', '\0'.

An array. You do need an array to hold characters. You do need a dynamically allocated array, not just one character. How large should that array be?

Copying values from one array to an another array usually involves a loop, although you might be able to use functions from header <cstring>.

What should happen on:
MyString ms( "Slartibartfast has Bistro-Math", 7);
Topic archived. No new replies allowed.