|
-
February 17th, 2013, 03:24 PM
#8
Re: Problem with loop in my beginner program
You can do that. If however you don't know the size of the changeable buffer, it is usually better to go with:
Code:
#include <vector>
typedef std::vector<char> CharArray;
//...
int main()
{
CharArray s(10); // an array of 10 chars, but much safer
int n = 30;
CharArray s2(n); // an array of n characters. You cannot do this with regular arrays
s2[0] = 'x'; // set the first character to x
}
Then when you want to pass the CharArray to another function that doesn't know anything about vectors, but only null-terminated strings, you pass the address of the first element of the vector.
Basically, you use the CharArray in the same way you were using the array of chars (it must be null-terminated also). The big difference with doing things using vectors as opposed to arrays is that array sizes must be known at compile-time, while vector sizes can be dynamic. Note the "n = 30" line, and how I used n to create a char array of n characters. Otherwise, you have to go the "new"/"delete" path, and I don't recommend it due to the extra pointer maintenance and probable memory leaks when introducing dynamically allocated memory.
The std::string class has recently made the internal buffer writeable, but to be safe for now, assume that you cannot write to the internal buffer. Therefore you have to use regular char arrays or std::vector<char> as writeable buffers (or use new[]/delete[], knowing all the caveats of going this route).
Regards,
Paul McKenzie
Last edited by Paul McKenzie; February 17th, 2013 at 03:28 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|