473,398 Members | 2,380 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

How to initialize a char*?

Hi,

So many times, I have seen compile warning: "you used a char* without
initilize it", probably on the code like this:

------------
char* ptr;

func(..., ptr);
----------

How to properly initialize a char*? I used to use

char* ptr = "";

but was told this is not good.

Can anybody explain to me why, and what's a good way to initilize it?

Thanks,
Peter
Jul 22 '05 #1
74 42882
Peter <yb***@yahoo.com> spoke thus:
char* ptr;
func(..., ptr);
This is bad - ptr is uninitialized (not even NULL), so passing it to a
function is either pointless or an invitation to disaster, a mistake
in any case.
How to properly initialize a char*? I used to use char* ptr = "";
Depends on what you're doing with it. You probably were told that
because it should be

const char *ptr="";

Why? Because "" is a constant empty string; trying to modify it
invites disaster. Therefore, pointers to such string literals (so
they're called) should be declared const; that way if you try to
modify what it points to the compiler can inform you of your mistake.
Can anybody explain to me why, and what's a good way to initilize it?


Done. Unless you have a specific reason not to, though, you should be
using std::strings so you won't have to worry about the preceding
stuff.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Jul 22 '05 #2
Peter wrote:

Hi,

So many times, I have seen compile warning: "you used a char* without
initilize it", probably on the code like this:

------------
char* ptr;

func(..., ptr);
----------

How to properly initialize a char*? I used to use

char* ptr = "";

but was told this is not good.

Can anybody explain to me why, and what's a good way to initilize it?


I'd suspect that it isn't recommended because it isn't really clear what ptr is
used for: it has a value pointing to a constant string that shouldn't be
modified, but can be.

When and where a pointer is necessary, you can initialize it as:

char* ptr = NULL;

Then, it is more obvious that the pointer has been initialized and points to
nothing, but that when it does point to something, the destination will be
modifiable.
Jul 22 '05 #3
"Peter" <yb***@yahoo.com> wrote in message
news:40******@rpc1284.daytonoh.ncr.com...
Hi,

So many times, I have seen compile warning: "you used a char* without
initilize it", probably on the code like this:

------------
char* ptr;

func(..., ptr);
----------

How to properly initialize a char*? I used to use

char* ptr = "";

but was told this is not good.
const char *ptr = "";

But this initializes 'ptr' with the address of
the first character of the string literal "".
The target of this pointer cannot be modified.

If you want to create an initialize a pointer whose
value you want to change later, just initialize it
to the address of some character, or to 0 (NULL).

char *ptr = 0;

Can anybody explain to me why, and what's a good way to initilize it?


It really depends upon what you're doing. As a general
rule, I try not to create an object until I have a meaningful
value available with which to initialize it. If no such
value is available, I'll 'default' initialize it, i.e. for a
pointer, with NULL.

Are you sure you wouldn't be better off using a std::string
object instead of a char pointer? std::string objects are
automatically initialized when created.

std::string s; /* initialized with empty string */

-Mike
Jul 22 '05 #4
Peter wrote:
Can anybody explain to me why, and what's a good way to initilize it?


In general the best way to initialize pointers is with null (that is, 0).
Jul 22 '05 #5
On Tue, 13 Apr 2004 11:19:38 -0700 in comp.lang.c++, "Peter"
<yb***@yahoo.com> wrote,
So many times, I have seen compile warning: "you used a char* without
initilize it", probably on the code like this:


Uninitialized variables are evil, whether pointers or otherwise,
although uninitialized pointers are the worst. Never define a variable
without initializing it, without the most extreme reason to do so.

You should get rid of all your (char *) pointers and replace them by
using std::string instead. std::string initializes itself by default to
an empty string, and everybody is happy.

Jul 22 '05 #6
Peter wrote:
Hi,

So many times, I have seen compile warning: "you used a char* without
initilize it", probably on the code like this:

------------
char* ptr;

func(..., ptr);
There's absolutely no reason to do this (unless possibly if the function
expects a non-const reference). The fact that you think you want to
suggests that you don't understand pointers yet, and/or this does not do
what you expect.

Never use any variable before you've given it a meaningful value. Doing
so gives undefined behavior, and could crash your program or worse.
----------

How to properly initialize a char*? I used to use

char* ptr = "";
This uses a dangerous and deprecated language feature -- the implicit
conversion of a string literal to a (non-const) char*. I'd suggest
making your compiler warn about this if it provides such a warning.

but was told this is not good.

Can anybody explain to me why, and what's a good way to initilize it?


Initialize it with whatever you need. You're the only one who knows what
purpose it serves, so we can't suggest what to use. But leaving it
uninitialized is an error, and doesn't make sense.

Also, use std::string instead of a char* if you need a string.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #7
Christopher Benson-Manica wrote:

Peter <yb***@yahoo.com> spoke thus:
char* ptr;
func(..., ptr);


This is bad - ptr is uninitialized (not even NULL), so passing it to a
function is either pointless or an invitation to disaster, a mistake
in any case.


Not true.

Presume that func is declared as:

void func(int input, char * & dest);

Your statement may only be correct if func is declared as:

void func(int input, char * dest);

Since the OP didn't include the prototype, no assumption can be made about the
validity of passing in ptr.
Jul 22 '05 #8
Julie <ju***@nospam.com> spoke thus:
Since the OP didn't include the prototype, no assumption can be made about the
validity of passing in ptr.


Well, okay - rats. Good call.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Jul 22 '05 #9
David Harmon wrote:

On Tue, 13 Apr 2004 11:19:38 -0700 in comp.lang.c++, "Peter"
<yb***@yahoo.com> wrote,
So many times, I have seen compile warning: "you used a char* without
initilize it", probably on the code like this:
Uninitialized variables are evil, whether pointers or otherwise,
although uninitialized pointers are the worst. Never define a variable
without initializing it, without the most extreme reason to do so.


Not true.

The (unintentional) misuse of uninitialized variables may lead to undefined
behavior.
You should get rid of all your (char *) pointers and replace them by
using std::string instead. std::string initializes itself by default to
an empty string, and everybody is happy.


Not true.

char *, std::string, or any other character container should be used
judiciously and appropriately, depending on the specific implementation needs.

std::string is generally the recommended choice for general-purpose character
string storage and handling.

Further, the OP didn't specify as to what the char * is used for -- either
pointing to an array of characters or a pointer to a single character. A char
* should be the type used when pointing to a single character (use of
std::string would not be appropriate).
Jul 22 '05 #10
On Tue, 13 Apr 2004 13:34:44 -0700 in comp.lang.c++, Julie
<ju***@nospam.com> wrote,
Presume that func is declared as:

void func(int input, char * & dest);


If so, it is an evil func. You can tell me which fatal error does it
have, buffer overflow, or thread-hostile static buffer, or dynamically
allocating memory that the caller will forget to free? It needs to be
rewritten to use std::string.

Jul 22 '05 #11
David Harmon wrote:

On Tue, 13 Apr 2004 13:34:44 -0700 in comp.lang.c++, Julie
<ju***@nospam.com> wrote,
Presume that func is declared as:

void func(int input, char * & dest);
If so, it is an evil func. You can tell me which fatal error does it
have, buffer overflow, or thread-hostile static buffer, or dynamically
allocating memory that the caller will forget to free? It needs to be
rewritten to use std::string.


You shouldn't be making blanket statement like this w/o knowing the OP's
intention.

Here is another example that is perfectly legitimate:

void func(char * const input, int word_number, char * & ptr_to_word);
// find word in input and store address in ptr

No allocations, no (thread-hostile???) static buffers, no overflow.
It needs to be rewritten to use std::string.


As I previously replied, char * is a perfectly legitimate and usable type.
Blanket statements such as "use std::string" serve no purpose.

The answer to the OP's question is simple and concise:

Initialize a char * w/ NULL.

All other sub-threads relating to the intention of the OP are conjecture w/o
further clarification and input from the OP.
Jul 22 '05 #12
> > Uninitialized variables are evil, whether pointers or otherwise,
although uninitialized pointers are the worst. Never define a variable
without initializing it, without the most extreme reason to do so.
Not true.

The (unintentional) misuse of uninitialized variables may lead to

undefined behavior.


This is true, but I think it would be fair to argue that it is always good
practice to initialize variables to something (most likely NULL or 0 in this
case). No harm comes from doing this (always initializing), whereas there
are many situations where NOT initializing will shoot you in the foot.

-Matt
Jul 22 '05 #13
Matt Wharton wrote:
Uninitialized variables are evil, whether pointers or otherwise,
although uninitialized pointers are the worst. Never define a variable
without initializing it, without the most extreme reason to do so.


Not true.

The (unintentional) misuse of uninitialized variables may lead to

undefined
behavior.


This is true, but I think it would be fair to argue that it is always good
practice to initialize variables to something (most likely NULL or 0 in this
case). No harm comes from doing this (always initializing), whereas there
are many situations where NOT initializing will shoot you in the foot.

-Matt


Yes, my statement was directed at the 'evil' part -- there is nothing 'evil'
about it, it just has the potential to lead to undefined behavior.

Absolutely, variables, as a general rule, should be initialized to a
standardized default value.
Jul 22 '05 #14
"Peter" <yb***@yahoo.com> wrote in message
news:40******@rpc1284.daytonoh.ncr.com...
Hi,

So many times, I have seen compile warning: "you used a char* without
initilize it", probably on the code like this:

------------
char* ptr;

func(..., ptr);
----------

How to properly initialize a char*? I used to use

char* ptr = "";

but was told this is not good.

Can anybody explain to me why, and what's a good way to initilize it?

Usually people who initialize, initialize it to 0.

Initialization to some initial value is a "religious" matter, that is some
strongly like to do it while others don't. The truth is that in reality
initialization doesn't protect you.


Ioannis Vranos

Jul 22 '05 #15
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message
news:c5**********@chessie.cirr.com...
Peter <yb***@yahoo.com> spoke thus:
char* ptr;
func(..., ptr);
This is bad - ptr is uninitialized (not even NULL), so passing it to a
function is either pointless or an invitation to disaster, a mistake
in any case.

Why?

How to properly initialize a char*? I used to use

char* ptr = "";


Depends on what you're doing with it. You probably were told that
because it should be

const char *ptr="";

And what would be the use of that?
Why? Because "" is a constant empty string; trying to modify it
invites disaster. Therefore, pointers to such string literals (so
they're called) should be declared const; that way if you try to
modify what it points to the compiler can inform you of your mistake.

The above is entirely, completely useless.


Ioannis Vranos

Jul 22 '05 #16
"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Presume that func is declared as:

void func(int input, char * & dest);

You can't do that!
Your statement may only be correct if func is declared as:

void func(int input, char * dest);

I do not think his statement is correct.


Ioannis Vranos

Jul 22 '05 #17
"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Here is another example that is perfectly legitimate:

void func(char * const input, int word_number, char * & ptr_to_word);
// find word in input and store address in ptr

I do not think it is. You can take references from pointers only in
templates. Even in this case passing an unitialised char * would not have
any bad effect by its own.
No allocations, no (thread-hostile???) static buffers, no overflow.
It needs to be rewritten to use std::string.


As I previously replied, char * is a perfectly legitimate and usable type.
Blanket statements such as "use std::string" serve no purpose.

The answer to the OP's question is simple and concise:

Initialize a char * w/ NULL.

Nope. If he chooses to make the unneeded initialisation he should use 0, NOT
NULL.


Ioannis Vranos

Jul 22 '05 #18
Ioannis Vranos wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Presume that func is declared as:

void func(int input, char * & dest);


You can't do that!


???

Sure you can -- a reference to a variable of type char *.
Your statement may only be correct if func is declared as:

void func(int input, char * dest);


I do not think his statement is correct.


I do not understand what your point is. To whom are you referring to by "his"?
Jul 22 '05 #19
On Tue, 13 Apr 2004 15:47:58 -0700 in comp.lang.c++, Julie
<ju***@nospam.com> wrote,
Yes, my statement was directed at the 'evil' part -- there is nothing 'evil'
about it, it just has the potential to lead to undefined behavior.


This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[6.14] What does the FAQ mean by "such-in-such is evil"?".
http://www.parashift.com/c++-faq-lite/

Jul 22 '05 #20
"Julie" <ju***@nospam.com> wrote in message
news:40**************@nospam.com...
Ioannis Vranos wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Presume that func is declared as:

void func(int input, char * & dest);


You can't do that!


???

Sure you can -- a reference to a variable of type char *.
Your statement may only be correct if func is declared as:

void func(int input, char * dest);


I do not think his statement is correct.


I do not understand what your point is. To whom are you referring to by

"his"?
Can you provide a working example with a main() using such a function
accepting char * &?


Ioannis Vranos

Jul 22 '05 #21
"Matt Wharton" <no*************@agilent.com_spam> wrote in message
news:10***************@cswreg.cos.agilent.com...

This is true, but I think it would be fair to argue that it is always good
practice to initialize variables to something (most likely NULL or 0 in this case). No harm comes from doing this (always initializing), whereas there
are many situations where NOT initializing will shoot you in the foot.

An example?

To make long things short, initialization doesn't protect you from anything.
The only thing that it could "protect you" in theory is in the call of
delete/delete[] family to an ititialised-to-0 pointer. In reality however
such a call occurs at the end of a process and you will have done more
things previously by mistake on that 0 initialised pointer (e.g.
dereferencing it) that would be equally disastrous/undefined.

Initialisation does not protect you from any mistake.


Ioannis Vranos

Jul 22 '05 #22
"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Absolutely, variables, as a general rule, should be initialized to a
standardized default value.


Not absolutely.


Ioannis Vranos

Jul 22 '05 #23
"Kevin Goodsell" <us*********************@neverbox.com> wrote in message
news:s_*****************@newsread1.news.pas.earthl ink.net...

Never use any variable before you've given it a meaningful value. Doing
so gives undefined behavior, and could crash your program or worse.
You reminded me a humorous text that i had read a long ago which i just
searched in google. Check it:

http://www.lysator.liu.se/c/ten-commandments.html
Of course it has nothing to do with the subject, but this "never" of yours
reminded it to me. :-)
This uses a dangerous and deprecated language feature -- the implicit
conversion of a string literal to a (non-const) char*. I'd suggest
making your compiler warn about this if it provides such a warning.
Eh?

Initialize it with whatever you need. You're the only one who knows what
purpose it serves, so we can't suggest what to use. But leaving it
uninitialized is an error, and doesn't make sense.


It is not an error!


Ioannis Vranos

Jul 22 '05 #24
Ioannis Vranos wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Here is another example that is perfectly legitimate:

void func(char * const input, int word_number, char * & ptr_to_word);
// find word in input and store address in ptr


I do not think it is. You can take references from pointers only in
templates. Even in this case passing an unitialised char * would not have
any bad effect by its own.


Reference to a pointer type is perfectly legal, and has nothing to do w/
templates.

If you feel that I'm wrong, please correct me by referencing the C++ standard.
No allocations, no (thread-hostile???) static buffers, no overflow.
It needs to be rewritten to use std::string.


As I previously replied, char * is a perfectly legitimate and usable type.
Blanket statements such as "use std::string" serve no purpose.

The answer to the OP's question is simple and concise:

Initialize a char * w/ NULL.


Nope. If he chooses to make the unneeded initialisation he should use 0, NOT
NULL.


NULL is perfectly acceptable, and is standard.
Jul 22 '05 #25
Ioannis Vranos wrote:
Can you provide a working example with a main() using such a function
accepting char * &?


How about you go ahead and try it, and learn for yourself.
Jul 22 '05 #26
David Harmon wrote:

On Tue, 13 Apr 2004 15:47:58 -0700 in comp.lang.c++, Julie
<ju***@nospam.com> wrote,
Yes, my statement was directed at the 'evil' part -- there is nothing 'evil'
about it, it just has the potential to lead to undefined behavior.


This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[6.14] What does the FAQ mean by "such-in-such is evil"?".
http://www.parashift.com/c++-faq-lite/


Thanks for pointing it out.

After reading, that section definitely comes off as infantile and
inappropriate. I'd much prefer a more precise (and less humanity-subjective)
term as 'evil'. But I didn't write that FAQ, nor have any plans to write one,
so MC is free to write what he wants. Regardless, that doesn't preclude me
from stating that 'evil' is a poor word choice when discussing programmatic
constructs and behaviors.
Jul 22 '05 #27
Ioannis Vranos wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Absolutely, variables, as a general rule, should be initialized to a
standardized default value.


Not absolutely.


Yes absolutely.

From now on, in order to be considered a productive participant, you may want
to include more than simple phrase answers and actually provide some insight
into the matter.
Jul 22 '05 #28
"Julie" <ju***@nospam.com> wrote in message
news:40**************@nospam.com...
Ioannis Vranos wrote:
Can you provide a working example with a main() using such a function
accepting char * &?


How about you go ahead and try it, and learn for yourself.

Why don't you try? Just provide an empty definition of a function getting
char *&), create a main() with a valid call to it and if it compiles post it
here (i am not kidding you will see).


Regards,

Ioannis Vranos

Jul 22 '05 #29
Ioannis Vranos wrote:

"Matt Wharton" <no*************@agilent.com_spam> wrote in message
news:10***************@cswreg.cos.agilent.com...

This is true, but I think it would be fair to argue that it is always good
practice to initialize variables to something (most likely NULL or 0 in

this
case). No harm comes from doing this (always initializing), whereas there
are many situations where NOT initializing will shoot you in the foot.


An example?

To make long things short, initialization doesn't protect you from anything.
The only thing that it could "protect you" in theory is in the call of
delete/delete[] family to an ititialised-to-0 pointer. In reality however
such a call occurs at the end of a process and you will have done more
things previously by mistake on that 0 initialised pointer (e.g.
dereferencing it) that would be equally disastrous/undefined.

Initialisation does not protect you from any mistake.


That is true.

Perhaps it would be better to term this as 'zero initialization', after all

char * ptr = (char *)12345;

is initialized, but not much better than leaving it uninitialized.
Jul 22 '05 #30
Julie wrote:
Nope. If he chooses to make the unneeded initialisation he should use 0, NOT
NULL.


NULL is perfectly acceptable, and is standard.


Yes. It's defined in the clocale, cstddef, cstdio, cstdlib, cstring,
ctime and cwchar headers. In my opinion it's preferable to use 0
because it's supported directly by the language.

--
Regards,
Buster.
Jul 22 '05 #31
Ioannis Vranos wrote:
Can you provide a working example with a main() using such a function
accepting char * &?


void f (char * &) { }
int main () { f (); }

--
Regards,
Buster.
Jul 22 '05 #32


Buster wrote:
Ioannis Vranos wrote:
Can you provide a working example with a main() using such a function
accepting char * &?

void f (char * &) { }
int main () { f (); }


Oops.

void f (char * &) { }
int main ()
{
char c;
char * p = & c;
f (p);
}

--
Regards,
Buster.
Jul 22 '05 #33
Ioannis Vranos wrote:
"Julie" <ju***@nospam.com> wrote
Ioannis Vranos wrote:
Can you provide a working example with a main() using such a function
accepting char * &?


How about you go ahead and try it, and learn for yourself.


Why don't you try? Just provide an empty definition of a function getting
char *&), create a main() with a valid call to it and if it compiles post it
here (i am not kidding you will see).


Ioannis, post one that doesn't compile. Your problem is elsewhere.

--
Regards,
Buster.
Jul 22 '05 #34
Ioannis Vranos wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40**************@nospam.com...
Ioannis Vranos wrote:
Can you provide a working example with a main() using such a function
accepting char * &?


How about you go ahead and try it, and learn for yourself.


Why don't you try? Just provide an empty definition of a function getting
char *&), create a main() with a valid call to it and if it compiles post it
here (i am not kidding you will see).

Regards,

Ioannis Vranos


I did this for myself long ago, and it compiled and worked just fine.

Feel free to try for yourself.
Jul 22 '05 #35
"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

NULL is perfectly acceptable, and is standard.

"The C++ Programming Language" 3rd Edition or Special Edition by Bjarne
Stroustrup (the creator of C++), page 88:

5.1.1 Zero [ptr.zero]

Zero (0) is an int. Because of standard conversions (§C.6.2.3), 0 can be
used as a constant of any
integral (§4.1.1), floatingpoint, pointer, or pointer to member type. The
type of zero will be determined
by context. Zero will typically (but not necessarily) be represented by the
bit pattern allzeros
of the appropriate size.

No object is allocated with the address 0. Consequently, 0 acts as a pointer
literal, indicating
that a pointer doesn't refer to an object.

In C, it has been popular to define a macro NULL to represent the zero
pointer. Because of
C++'s tighter type checking, the use of plain 0, rather than any suggested
NULL macro, leads to
fewer problems. If you feel you must define NULL, use

const int NULL = 0;

The const qualifier (§5.4) prevents accidental redefinition of NULL and
ensures that NULL can be
used where a constant is required.

By the way it is an excellent book, i have been reading it on my own. I
strongly suggest it.


Ioannis Vranos

Jul 22 '05 #36
"Buster" <no***@nowhere.com> wrote in message
news:c5**********@newsg2.svr.pol.co.uk...

Ioannis, post one that doesn't compile. Your problem is elsewhere.

void func(char * const input, int word_number, char * & ptr_to_word)
{
}
int main()
{
char array[]="b";
func("a",5, array);
}


Ioannis Vranos

Jul 22 '05 #37
"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

That is true.

Perhaps it would be better to term this as 'zero initialization', after all
char * ptr = (char *)12345;

is initialized, but not much better than leaving it uninitialized.

Ok, so zero-initialisation or any other "premature" initialisation does not
protect you from anything. Btw try using the new C++ casts instead (of
course avoid them completely if possible).


Regards,

Ioannis Vranos

Jul 22 '05 #38
Ioannis Vranos wrote:

"Buster" <no***@nowhere.com> wrote in message
news:c5**********@newsg2.svr.pol.co.uk...

Ioannis, post one that doesn't compile. Your problem is elsewhere.


void func(char * const input, int word_number, char * & ptr_to_word)
{
}

int main()
{
char array[]="b";

func("a",5, array);
}

Ioannis Vranos


Yes, your problem is elsewhere.

The function takes a reference argument of type char *, you are (attempting) to
pass a type of char[2].

Here is your hat and coat.
Jul 22 '05 #39
"Buster" <no***@nowhere.com> wrote in message
news:c5**********@newsg2.svr.pol.co.uk...


void f (char * &) { }
int main ()
{
char c;
char * p = & c;
f (p);
}


But this doesn't compile:

void f (char * &) { }

int main ()
{
char c;
f (&c);
}


Ioannis Vranos

Jul 22 '05 #40
>Can you provide a working example with a main() using such a function
accepting char * &?


A library function I developed dynamically allocated data which it then passed
to a callback. The callback had the option of assuming ownership of that
dynamically allocated data. The callback had an argument of type reference to
pointer to type T. If the callback wanted to assume ownership of the
dynamically allocated data it could do so by copying the referenced pointer and
then setting the referenced pointer to zero. The library would then attempt to
delete a null pointer, which of course is a safe operation. If the callback
did not want to assume ownership of the dynamically allocated data then it did
not modify the referenced pointer. In that case the library deleted the
dynamically allocated data.

typedef void (*DataUser)(char*&);

void DataCreator(DataUser dataUser)
{
char *data = new char(0);
dataUser(data);
delete data;
}

void DataUser1(char*& data)
{
//Make copy of data for later usage and deletion
data = 0;
}

void DataUser2(char*&)
{
}

int main()
{
DataCreator(DataUser1);
DataCreator(DataUser2);

return 0;
}
Brian F. Seaberg
Naperville, Illinois
Delray Beach, Florida
Jul 22 '05 #41
Ioannis Vranos wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

That is true.

Perhaps it would be better to term this as 'zero initialization', after

all

char * ptr = (char *)12345;

is initialized, but not much better than leaving it uninitialized.


Ok, so zero-initialisation or any other "premature" initialisation does not
protect you from anything. Btw try using the new C++ casts instead (of
course avoid them completely if possible).

Regards,

Ioannis Vranos


How do you define when "premature" is "post-mature"?

The c-style cast was used for absolute simplicity, not as a model for casting.
Jul 22 '05 #42
"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...
Ioannis Vranos wrote:

"Buster" <no***@nowhere.com> wrote in message
news:c5**********@newsg2.svr.pol.co.uk...

Ioannis, post one that doesn't compile. Your problem is elsewhere.
void func(char * const input, int word_number, char * & ptr_to_word)
{
}

int main()
{
char array[]="b";

func("a",5, array);
}

Ioannis Vranos


Yes, your problem is elsewhere.

The function takes a reference argument of type char *, you are

(attempting) to pass a type of char[2].

A type of what?
Here is your hat and coat.

Check this out:
#include <iostream>
int main()
{
using namespace std;

char array[]="12345";

*array='X';

cout<<array<<endl;
}


Ioannis Vranos

Jul 22 '05 #43
"DaKoadMunky" <da*********@aol.com> wrote in message
news:20***************************@mb-m20.aol.com...
Can you provide a working example with a main() using such a function
accepting char * &?
A library function I developed dynamically allocated data which it then

passed to a callback. The callback had the option of assuming ownership of that
dynamically allocated data. The callback had an argument of type reference to pointer to type T. If the callback wanted to assume ownership of the
dynamically allocated data it could do so by copying the referenced pointer and then setting the referenced pointer to zero. The library would then attempt to delete a null pointer, which of course is a safe operation. If the callback did not want to assume ownership of the dynamically allocated data then it did not modify the referenced pointer. In that case the library deleted the
dynamically allocated data.

typedef void (*DataUser)(char*&);

void DataCreator(DataUser dataUser)
{
char *data = new char(0);
dataUser(data);
delete data;
}

void DataUser1(char*& data)
{
//Make copy of data for later usage and deletion
data = 0;
}

void DataUser2(char*&)
{
}

int main()
{
DataCreator(DataUser1);
DataCreator(DataUser2);

return 0;

Yes it works only for a straight char * pointer. Check this:
It doesn't compile:

void f (char * &) { }

int main ()
{
char c;
f (&c);
}

Yes i meant that we can't pass an object by using it's address directly as
in code:

void f(char * &x)
{
*x='a';
}
int main()
{
char c='a';

f(&c);
}

since there is not a real pointer object so it cannot assign a reference. I
was talking about convenience. I expressed myself erroneously, apologies it
is ~04:00 here...


Ioannis Vranos

Jul 22 '05 #44
"Ioannis Vranos" <iv*@guesswh.at.emails.ru> wrote in message
news:c5***********@ulysses.noc.ntua.gr...

Yes it works only for a straight char * pointer. Check this:
It doesn't compile:

void f (char * &) { }

int main ()
{
char c;
f (&c);
}

Yes i meant that we can't pass an object by using it's address directly as
in code:

void f(char * &x)
{
*x='a';
}
int main()
{
char c='a';

f(&c);
}

since there is not a real pointer object so it cannot assign a reference. I was talking about convenience. I expressed myself erroneously, apologies it is ~04:00 here...

which is obvious since i posted twice above. :-)


Ioannis Vranos

Jul 22 '05 #45
"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Ok, so zero-initialisation or any other "premature" initialisation does not protect you from anything. Btw try using the new C++ casts instead (of
course avoid them completely if possible).

Regards,

Ioannis Vranos


How do you define when "premature" is "post-mature"?

"premature"=initial value not actually intended to be used.
Too tired, going off line now. Good day/night there.


Ioannis Vranos

Jul 22 '05 #46
Ioannis Vranos wrote:
"Buster" <no***@nowhere.com> wrote

void f (char * &) { }
int main ()
{
char c;
char * p = & c;
f (p);
}


But this doesn't compile:

void f (char * &) { }

int main ()
{
char c;
f (&c);
}


Of course not. What would it do if it did compile?
Modify the address of c?

--
Regards,
Buster.
Jul 22 '05 #47
On Wed, 14 Apr 2004 03:50:55 +0300,
Ioannis Vranos <iv*@guesswh.at.emails.ru> wrote:
"Buster" <no***@nowhere.com> wrote in message
news:c5**********@newsg2.svr.pol.co.uk...


void f (char * &) { }
int main ()
{
char c;
char * p = & c;
f (p);
}


But this doesn't compile:

void f (char * &) { }

int main ()
{
char c;
f (&c);
}


Because the const-ness is incorrect.

"char * &" is not the same as "char * const &".

--
Sam Holden
Jul 22 '05 #48
Sam Holden wrote:

Iannis Vranos <iv*@guesswh.at.emails.ru> wrote:

But this doesn't compile:

void f (char * &) { }

int main ()
{
char c;
f (&c);
}


Because the const-ness is incorrect.

"char * &" is not the same as "char * const &".


Kind of. The type of "& c" is not "char * const &". In fact, "& c"
is an rvalue of type "char *". It is true that you can compile

void f (char * const &) { }

int main ()
{
char c;
f (& c);
}

This is because you can bind a const reference to an rvalue.

--
Regards,
Buster.
Jul 22 '05 #49
On Tue, 13 Apr 2004 17:08:50 -0700, Julie <ju***@nospam.com> wrote:
David Harmon wrote:

On Tue, 13 Apr 2004 15:47:58 -0700 in comp.lang.c++, Julie
<ju***@nospam.com> wrote,
>Yes, my statement was directed at the 'evil' part -- there is nothing 'evil'
>about it, it just has the potential to lead to undefined behavior.


This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[6.14] What does the FAQ mean by "such-in-such is evil"?".
http://www.parashift.com/c++-faq-lite/


Thanks for pointing it out.

After reading, that section definitely comes off as infantile and
inappropriate. I'd much prefer a more precise (and less humanity-subjective)
term as 'evil'. But I didn't write that FAQ, nor have any plans to write one,
so MC is free to write what he wants. Regardless, that doesn't preclude me
from stating that 'evil' is a poor word choice when discussing programmatic
constructs and behaviors.


Probably a bit too late to derail the use of "evil" in this context. Herb
Sutter, Scott Meyers and others have pretty much blessed it and it is here
to stay. I think saying "X is evil" concisely and effectively conveys the
message "X is a legal syntactic construct that, IMHO, if not executed with
the utmost care bordering on radical paranoia, is about as likely as
anything else you can write in this language to lead you down the slippery
slope into deep doo-doo, and then make it very hard for you to slog your
way back out."
-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Kai Wu | last post by:
#include <string.h> #include <fstream> #include <time.h> typedef unsigned char BYTE; struct Dex { BYTE status; struct timeval timestamp; }; int main(){
5
by: Anton Pervukhin | last post by:
Hello! Imagine the situation you have a class that interprets the command line of the program you are executing. This class is written by third party and has a main function parse with arguments...
17
by: Rick | last post by:
Hi, Before copying something into a character array, do we need to initialize it with something? For example: char a; strcpy(a, "hey"); Can we do:
4
by: rasika | last post by:
I have a structure typedef struct m { char *name, char **alais; }mystruct; The way I have initialised name field of the struct i want to intialise the alais field to { "geeta", NULL } char...
10
by: Yang Lee | last post by:
hi is this correct char teststr="\0"; or is there another method to initialise; thanks lee
2
by: shan_rish | last post by:
Hi CLCers, In the below program the error message while compiling is /home1/murugan/prog/cprog >cc -o struct_eval struct_eval.c cc: "struct_eval.c", line 14: error 1549: Modifiable lvalue...
2
by: msnews.microsoft.com | last post by:
Hi! In C++ you could easily intialize a char-variable with an integer value: char ch = 123; How can we accomplish this in C#? You can get the integer representation of a char value easily,...
10
by: Dancefire | last post by:
Hi, everyone, I'm writing a program using wstring(wchar_t) as internal string. The problem is raised when I convert the multibyte char set string with different encoding to wstring(which is...
9
by: ashokd001 | last post by:
Hi How do i reinitialize a char array in one line if i want to use the same array variable every time. Ex- char name; -Ashok
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.