What you should do is probably read a good lesson on pointers and arrays, and their relationship with each other.
The idea behind a C-style string is that it is a sequence of characters that end with a '\0' char. In C, you do this with an array, where each element of the array holds one character, including the ending '\0' char. Where pointers come in is that arrays are often referred to simply by a pointer to the first element in the array. Since arrays are stored sequentially in memory, you can easily find each character of the string by simply walking through the memory until you reach the terminating '\0' char.
What you have in your code section is, first of all, a pointer named a that points to a block of memory. You then have a pointer named b that points to some random place because you didn't initialize it to point anywhere. It doesn't point to the first element of any valid array at this point. Therefore, you can't copy stuff to it. You're doing it anyway in the loop, and this will result in undefined behavior (most likely your program crashing in this case).
What you should do is something similar to this:
Code:
#include <iostream>
#include <cstdlib>
int main(int argc, char *argv[])
{
int i;
char *a = "String 1";
char *b = (char *)malloc(strlen(a)+1); /* Note, casting is needed because this is C++. */
for(i=0;a[i] != '\0';i++)
{
b[i] = a[i];
}
b[i] = '\0';
std::cout << "a: " << a << std::endl;
std::cout << "b: " << b << std::endl;
free(b);
return 0;
}
There are much better ways of writing this, however, this should be straightforward enough to understand the concept behind it.
Now with that said......
You should be using C++ strings instead of C-style strings when you can. C++ strings are much safer and easier to deal with.
Code:
#include <iostream>
int main(int argc, char *argv[])
{
std::string a("String 1");
std::string *b;
b = new std::string(a);
std::cout << a << std::endl;
std::cout << *b << std::endl;
delete b;
return 0;
}