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.
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?
*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.
Pointer is a variable that holds one value. A number. The number means a memory address.
In constchar * 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);