Question about pointers

This is a discussion on Question about pointers within the C++ Programming forums, part of the General Programming Boards category; I am a budding C/C++ programmer and so I am of course having trouble dealing with the concept of pointers. ...

Question about pointers

I am a budding C/C++ programmer and so I am of course having trouble dealing with the concept of pointers. Not pointers in and of themselves, but using pointers as strings. I have several questions but will post them seperately. My first question is about setting a pointer equal to a string. I will present 2 snippets of code, please tell me which, if any, is valid and why. Thank you for the help everyone.

1)
char* string = new char[10]; //create a string and initialize memory for 10 characters
string = "123456789"; //use the equals operator to set it equal to a 9 character string.

So, basically what I want to know is, can you set a pointer equal to a string, or do you have to set each cell manually? My other question is, if I have allocated enough space for 10 characters, and put 10 characters into it, is that overflowing memory because of the null terminator at the end?

Remember in your example string is a pointer. It points to a memory address. When you tried to assign a string literal to it that will cause a problem. Your second example would work but not give you the results you expect. You are assigning the integer values 0 through 9. These represent different ascii characters than '0' '1', etc. You would have to do something like

Code:

for( int i = 0; i < 10; ++i )
{
string[i] = '0' + i;
}

That would give you the correct ascii value. Also you are correct. You want to add one element to your allocation for the null terminator. If you assign each element individually you will have to manually put the terminator in. If you use strcpy it will do that for you.

"...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers