char*

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
littledump
New poster
Posts: 25
Joined: Wed Jun 05, 2002 4:55 am
Location: London, ON, Canada
Contact:

char*

Post by littledump »

is using char* the best method for a varying length string?

i dont think it is because ive tried to use a char* with sprintf & i get null pointer assignment.

whats an alternative? make a really big char array?
Stefan Pochmann
A great helper
Posts: 284
Joined: Thu Feb 28, 2002 2:00 am
Location: Germany
Contact:

Post by Stefan Pochmann »

Did you allocate memory or just used the pointer without doing so? In the latter case it's no wonder you get a "null pointer exception" (I assume that's what you got, not an "assignment").

Solutions if you need to make a string longer:
- Reallocate memory.
- Use a large array from the start.
- Use string objects of C++.
littledump
New poster
Posts: 25
Joined: Wed Jun 05, 2002 4:55 am
Location: London, ON, Canada
Contact:

Post by littledump »

how do u reallocate memory & how do i use the string object?

also i tried declaring a BOOL variable but got an error.


using borland c++ 3.0 for dos
Stefan Pochmann
A great helper
Posts: 284
Joined: Thu Feb 28, 2002 2:00 am
Location: Germany
Contact:

Post by Stefan Pochmann »

You can use the old C functions malloc, calloc, free and realloc, but I'd suggest the newer C++ variants:

char *str;

str = new char[1000];
... (use str)
delete[] str;

str = new char[10000];
... (use str)
delete[] str;

Try writing "bool" (lowercase letters).

Using a string:

string str = "abc";
cout << str << endl;
str += "def";
cout << str << endl;
littledump
New poster
Posts: 25
Joined: Wed Jun 05, 2002 4:55 am
Location: London, ON, Canada
Contact:

Post by littledump »

ive tried bool in lowercase & i dont thing my compiler has that string object.

mebbe time for new compiler
Stefan Pochmann
A great helper
Posts: 284
Joined: Thu Feb 28, 2002 2:00 am
Location: Germany
Contact:

Post by Stefan Pochmann »

"bool" should really be there, and "string" when you include it:
include <string>

Don't say
include <string.h>

that will only include the old C header file for string stuff. And just in case you want that, it should actually be
include <cstring>

instead.
littledump
New poster
Posts: 25
Joined: Wed Jun 05, 2002 4:55 am
Location: London, ON, Canada
Contact:

Post by littledump »

i get an error when trying to include <string>. it doesnt exist

and bool doesnt work.

mebbe someone with borland will enlighten me
Adrian Kuegel
Guru
Posts: 724
Joined: Wed Dec 19, 2001 2:00 am
Location: Germany

Post by Adrian Kuegel »

I don't use Borland C++, but try this:
#include <string>
using namespace std;

string test;
...
Post Reply

Return to “C++”