By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,852 Members | 2,219 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,852 IT Pros & Developers. It's quick & easy.

Is this correct?

P: n/a
Hi,

If I write

char *p="hello world";

is this correct in C or do i have to assign memory block and then
strcpy the string to pointer.

If not correct in C , is it allowable in C++ , i seen such syntax in
some books of c++;

thanks
lee
--
Posted via Mailgate.ORG Server - http://www.Mailgate.ORG
Nov 14 '05 #1
Share this Question
Share on Google+
27 Replies


P: n/a
On Tue, 16 Dec 2003 05:53:01 +0000 (UTC), "Yang Lee"
<ya*******@ausi.com> wrote in comp.lang.c:
Hi,

If I write

char *p="hello world";

is this correct in C or do i have to assign memory block and then
strcpy the string to pointer.

If not correct in C , is it allowable in C++ , i seen such syntax in
some books of c++;

thanks
lee


This is correct in both C and C++.

The pointer p is initialized to point to the first character of the
unnamed array of characters holding the string literal.

In C++, the type of this array is array of constant char. In C the
language does not specify whether the string literal is constant or
not. But in both languages, it is undefined behavior is you try to
modify the string literal.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 14 '05 #2

P: n/a
Lee,

On Tue, 16 Dec 2003 05:53:01 UTC, "Yang Lee" <ya*******@ausi.com> wrote:
Hi,

If I write

char *p="hello world";

is this correct in C or do i have to assign memory block and then
strcpy the string to pointer.
This is correct in C and C++.

The quoted text ("hello world") will be stored in the progams memory
space. The pointer p will point to this string in memory.

The size of the ("hello world") memory block is likely to be 12 bytes.
If you just want this to be used as a constant or for a string space
that is less than the original memory block that is okay. If you were
to copy a larger string over this definition of p, you would overwrite
some part of memory that you do not know what it is. That can be
dangerous.
If not correct in C , is it allowable in C++ , i seen such syntax in
some books of c++;

thanks
lee


David
Nov 14 '05 #3

P: n/a
David wrote:
Lee,

On Tue, 16 Dec 2003 05:53:01 UTC, "Yang Lee" <ya*******@ausi.com> wrote:

Hi,

If I write

char *p="hello world";

is this correct in C or do i have to assign memory block and then
strcpy the string to pointer.

This is correct in C and C++.

The quoted text ("hello world") will be stored in the progams memory
space. The pointer p will point to this string in memory.

The size of the ("hello world") memory block is likely to be 12 bytes.
If you just want this to be used as a constant or for a string space
that is less than the original memory block that is okay. If you were
to copy a larger string over this definition of p, you would overwrite
some part of memory that you do not know what it is. That can be
dangerous.


This is blatantly wrong. Any attempt to modify a string literal results
in undefined behavior. It doesn't matter at all whether the new string
is shorter or longer than the old. Undefined is undefined.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #4

P: n/a
Yang Lee wrote:
Hi,

If I write

char *p="hello world";

is this correct in C or do i have to assign memory block and then
strcpy the string to pointer.

If not correct in C , is it allowable in C++ , i seen such syntax in
some books of c++;


It's technically allowed, but almost always a mistake. In C++ it is
deprecated.

String literals may not be modified, therefore pointers to string
literals should be const. This allows the compiler to warn you if you
attempt to modify a string literal. Otherwise the likely result will be
a crash at runtime.

So while this is allowed:

char *p = "some string";

You should never use it. Use one of these instead:

const char *p = "some string";
char const *p = "some string";
const char * const p = "some string";
char const * const p = "some string";

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #5

P: n/a

"David" <Fl************@United.Com> schrieb im Newsbeitrag
news:rOdGr40LMPU3-pn2-1QSv7ZdRdo5l@localhost...
Lee,

On Tue, 16 Dec 2003 05:53:01 UTC, "Yang Lee" <ya*******@ausi.com> wrote:
Hi,

If I write

char *p="hello world";

is this correct in C or do i have to assign memory block and then
strcpy the string to pointer.
This is correct in C and C++.

The quoted text ("hello world") will be stored in the progams memory
space. The pointer p will point to this string in memory.

The size of the ("hello world") memory block is likely to be 12 bytes.
If you just want this to be used as a constant or for a string space
that is less than the original memory block that is okay. If you were
to copy a larger string over this definition of p, you would overwrite
some part of memory that you do not know what it is. That can be
dangerous.


If he tries to modify _any_ part of this string literal, _very_ surprising
things may happen :)
strcpy(p, "my world");
will segfault if he is lucky. With some bad luck it will format his
harddisk, destroy his monitor (both can _really_ happen, believe me).
On a DS9000 an iron hand may come out of the CD drive and hit his nose :)
(which is one of the less nasty reactions of a DS9000 if it encounters UB).
If not correct in C , is it allowable in C++ , i seen such syntax in
some books of c++;


It is perfectly correct in C, but it is _not_ allowed to modify the string
literal.
Robert
Nov 14 '05 #6

P: n/a
"Robert Stankowic" <pc******@netway.at> writes:
If he tries to modify _any_ part of this string literal, _very_ surprising
things may happen :)
strcpy(p, "my world");
will segfault if he is lucky. With some bad luck it will format his
harddisk, destroy his monitor (both can _really_ happen, believe me).


Very true. A `void main (int argc, char **argv)' (in a program not written
by me) almost destroyed my monitor once. I could only save it by pulling
the power plug.

Martin
Nov 14 '05 #7

P: n/a

"Martin Dickopp" <ex****************@zero-based.org> schrieb im Newsbeitrag
news:br*************@news.t-online.com...
"Robert Stankowic" <pc******@netway.at> writes:
If he tries to modify _any_ part of this string literal, _very_ surprising things may happen :)
strcpy(p, "my world");
will segfault if he is lucky. With some bad luck it will format his
harddisk, destroy his monitor (both can _really_ happen, believe me).


Very true. A `void main (int argc, char **argv)' (in a program not written
by me) almost destroyed my monitor once. I could only save it by pulling
the power plug.


Yep. And a "wild" pointer (under DOS, with Watcom C) once really caused the
program to crash into the low level format routine and happily formatted my
HD.
It could, btw, as well play Tchernobyl and destroy certain brands of
mainboards with a writeable, but soldered BIOS chip.
Such is (C) life :)
Nov 14 '05 #8

P: n/a
Martin Dickopp <ex****************@zero-based.org> writes:
"Robert Stankowic" <pc******@netway.at> writes:
If he tries to modify _any_ part of this string literal, _very_ surprising
things may happen :)
strcpy(p, "my world");
will segfault if he is lucky. With some bad luck it will format his
harddisk, destroy his monitor (both can _really_ happen, believe me).


Very true. A `void main (int argc, char **argv)' (in a program not written
by me) almost destroyed my monitor once. I could only save it by pulling
the power plug.


Seriously? If you can provide details, your story could be excellent
ammunition in arguments with who equate "it works for me" with "it's
correct".

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #9

P: n/a

"Yang Lee" <ya*******@ausi.com> wrote in message

If I write

char *p="hello world";

is this correct in C or do i have to assign memory block and then
strcpy the string to pointer.
It is correct, but normally you would just pass the string literal to the
function that needs it.

eg printf("Hello world");

rather than
char *p = "Hello world";
printf(p);

if you need modify the string, you do need to copy to an array

eg

char str[256];

strcpy(str, "Hello world");
strcat(str, " from Yang Lee");
If not correct in C , is it allowable in C++ , i seen such syntax in
some books of c++;

It's rather old-fashioned C++. Modern C++ would use the string class to
store string literals.
Nov 14 '05 #10

P: n/a
Kevin Goodsell <us*********************@neverbox.com> wrote in
news:6X*****************@newsread2.news.pas.earthl ink.net:

const char *p = "some string";
char const *p = "some string";
const char * const p = "some string";
char const * const p = "some string";


What are the differences, if any, between these definitions?
P.Krumins
Nov 14 '05 #11

P: n/a
On 16 Dec 2003 23:35:20 GMT, in comp.lang.c , Peteris Krumins
<pk****************@inbox.lv> wrote:

read from right to left.
const char *p = "some string";
p is a pointer to char which is const...
ie pointer to const char
char const *p = "some string";
const pointer to char
const char * const p = "some string";
const pointer to const char
char const * const p = "some string";


syntax error

In all cases, the data pointed to is a string literal, which is by
definition nonmodifiable anyway.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #12

P: n/a
Mark McIntyre <ma**********@spamcop.net> wrote:
On 16 Dec 2003 23:35:20 GMT, in comp.lang.c , Peteris Krumins
<pk****************@inbox.lv> wrote: read from right to left.
Are you sure that that's what you're doing?
const char *p = "some string"; p is a pointer to char which is const...
ie pointer to const char char const *p = "some string"; const pointer to char
Nope, it is equivalent to the first example. Const pointer
to char would be:

char * const p;
const char * const p = "some string"; const pointer to const char char const * const p = "some string";

syntax error


Nope. Again, as above, const pointer to const char.

Alex
Nov 14 '05 #13

P: n/a
I wrote:
[...]
Seriously? If you can provide details, your story could be excellent
ammunition in arguments with who equate "it works for me" with "it's
correct".


That should be "... arguments with *people* who equate ...".

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #14

P: n/a
Peteris Krumins wrote:
Kevin Goodsell <us*********************@neverbox.com> wrote in
news:6X*****************@newsread2.news.pas.earthl ink.net:

const char *p = "some string";
char const *p = "some string";
const char * const p = "some string";
char const * const p = "some string";

What are the differences, if any, between these definitions?


Unless I've made a mistake, the first two are equivalent to each other,
and the last two are equivalent to each other.

The first two both mean that p is a pointer to type const char. In other
words, the pointer may be modified (made to point elsewhere), but you
may not use that pointer for the purpose of modifying the object to
which it points.

The last two both mean that p is a const pointer to type const char. The
pointer cannot be made to point elsewhere, nor can the thing to which it
points be modified via the pointer.

So, the only difference is whether or not you can reassign p to point
somewhere else.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #15

P: n/a

"Keith Thompson" <ks***@mib.org> schrieb im Newsbeitrag
news:ln************@nuthaus.mib.org...
Martin Dickopp <ex****************@zero-based.org> writes:
"Robert Stankowic" <pc******@netway.at> writes:
If he tries to modify _any_ part of this string literal, _very_ surprising things may happen :)
strcpy(p, "my world");
will segfault if he is lucky. With some bad luck it will format his
harddisk, destroy his monitor (both can _really_ happen, believe me).


Very true. A `void main (int argc, char **argv)' (in a program not written by me) almost destroyed my monitor once. I could only save it by pulling
the power plug.


Seriously? If you can provide details, your story could be excellent
ammunition in arguments with who equate "it works for me" with "it's
correct".

<OT>
Why not? void main() may cause a (non protected) implementation to mess up
the stack upon return from main(), run wild and set the screen resolution to
something the monitor cannot handle. On some old monitors the result is
disastrous.

"Taking over in poor visibility worked always for me" said the guy when he
woke up in the hospital....
</OT>
Nov 14 '05 #16

P: n/a
Kevin Goodsell wrote:

(snip)
char *p="hello world";

(snip)
The size of the ("hello world") memory block is likely to be 12 bytes.
If you just want this to be used as a constant or for a string space
that is less than the original memory block that is okay. If you were
to copy a larger string over this definition of p, you would overwrite
some part of memory that you do not know what it is. That can be
dangerous.
This is blatantly wrong. Any attempt to modify a string literal results
in undefined behavior. It doesn't matter at all whether the new string
is shorter or longer than the old. Undefined is undefined.


For compatibility with K&R C it has to be allowed. I know some
compilers have it as an option. Others may not have the
compatibility mode anymore.

-- glen

Nov 14 '05 #17

P: n/a
glen herrmannsfeldt <ga*@ugcs.caltech.edu> spoke thus:
For compatibility with K&R C it has to be allowed. I know some
compilers have it as an option. Others may not have the
compatibility mode anymore.


K&R2, p194:
"...the behavior of a program that attempts to alter a string
literal is undefined."

I assume by K&R C you're speaking of pre-ANSI...?

--
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.
Nov 14 '05 #18

P: n/a
Keith Thompson <ks***@mib.org> writes:
Martin Dickopp <ex****************@zero-based.org> writes:
Very true. A `void main (int argc, char **argv)' (in a program not written
by me) almost destroyed my monitor once. I could only save it by pulling
the power plug.


Seriously? If you can provide details, your story could be excellent
ammunition in arguments with who equate "it works for me" with "it's
correct".


I was configuring suspend-to-disk on my GNU/Linux system, and it turned
out that the graphics state was not properly restored, resulting in a
messed up screen. Luckily, the problem could be avoided by switching to
text mode before suspending, and switching back to graphics mode after
resuming.

I didn't want to do this manually, so I modified the scripts which are run
before suspending and after resuming to switch to a text console and back.
Unfortunately, the `main' function of the program to switch virtual
terminals returned `void'. The undefined behaviour in this case had the
effect that the program incorrectly reported unsuccessful execution after
switching virtual terminals. This in turn caused the script to terminate
immediately and report unsuccessful execution to its own parent process,
the power management daemon.

An unrelated BIOS bug (maybe it was supposed to be a feature...) caused
the BIOS to retry immediately if suspend-to-disk failed. The effect was
that the system switched forth and back between graphics and text mode in
fast succession. Monitors don't like that... :)

Martin
Nov 14 '05 #19

P: n/a
Christopher Benson-Manica <at***@nospam.cyberspace.org> wrote:
glen herrmannsfeldt <ga*@ugcs.caltech.edu> spoke thus:
For compatibility with K&R C it has to be allowed. I know some
compilers have it as an option. Others may not have the
compatibility mode anymore.

K&R2, p194:
"...the behavior of a program that attempts to alter a string
literal is undefined." I assume by K&R C you're speaking of pre-ANSI...?


K&R C is C as defined by K&R 1. Obviously pre-ANSI.

Alex
Nov 14 '05 #20

P: n/a
Jack Klein wrote:
The pointer p is initialized to point to the first character of the
unnamed array of characters holding the string literal.

In C++, the type of this array is array of constant char. In C the
language does not specify whether the string literal is constant or
not. But in both languages, it is undefined behavior is you try to
modify the string literal.
#include <stdio.h>
void func(char * p);

int main(void)
{
char * p = "abcdefg";
printf("%s\n", p);
func(p);

return 0;
}

void func(char * p)
{
*(p + 2) = 'z';
printf("%s\n", p);
}

This "seems" to work. The string literal is modified. Is this
undefined behaviour? If so, can I take advantage of it if the
code runs only on platform x with implementation y? That is, is
the behaviour consistent for a particular platform and
implementation, albeit undefined?

Nov 14 '05 #21

P: n/a
Elliot Marks <em****@email.net> writes:
Jack Klein wrote:
The pointer p is initialized to point to the first character of the
unnamed array of characters holding the string literal.
In C++, the type of this array is array of constant char. In C the
language does not specify whether the string literal is constant or
not. But in both languages, it is undefined behavior is you try to
modify the string literal.
#include <stdio.h>
void func(char * p);

int main(void)
{
char * p = "abcdefg";
printf("%s\n", p);
func(p);

return 0;
}

void func(char * p)
{
*(p + 2) = 'z';


p[2] is more straightforward.
printf("%s\n", p);
}

This "seems" to work. The string literal is modified. Is this
undefined behaviour?
Yes.
If so, can I take advantage of it if the code runs only on
platform x with implementation y? That is, is the behaviour
consistent for a particular platform and implementation, albeit
undefined?


If an implementation provides a definition of some form of
undefined behavior, then you can depend on it when you use that
implementation (only).
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Nov 14 '05 #22

P: n/a
Martin Dickopp <ex****************@zero-based.org> writes:
[...]
I didn't want to do this manually, so I modified the scripts which are run
before suspending and after resuming to switch to a text console and back.
Unfortunately, the `main' function of the program to switch virtual
terminals returned `void'. The undefined behaviour in this case had the
effect that the program incorrectly reported unsuccessful execution after
switching virtual terminals. This in turn caused the script to terminate
immediately and report unsuccessful execution to its own parent process,
the power management daemon.


So the effect wasn't caused by a corruption of the stack (i.e.,
leaving the stack pointer pointing to an incorrect location), just by
main() returning an arbitrary value that the caller assumed was
meaningful. I suspect the same thing would have happened if main()
had been properly declared to return int, but without a return or
exit().

I know that corrupting the stack (by failing to return a value) is one
plausible consequence of void main(), but I don't think I've ever
heard of a system where it actually happens. On many systems, an int
result is returned in a register; a void function just leaves garbage
in that register. On most other systems, I think, either the caller
leaves room for a result regardless of the declaration, or the calling
code restores the stack pointer correctly regardless of what the
called function does with it.

It's still a great example, of course.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #23

P: n/a
On Wed, 17 Dec 2003 20:01:35 GMT
Elliot Marks <em****@email.net> wrote:
Jack Klein wrote:
The pointer p is initialized to point to the first character of the
unnamed array of characters holding the string literal.

In C++, the type of this array is array of constant char. In C the
language does not specify whether the string literal is constant or
not. But in both languages, it is undefined behavior is you try to
modify the string literal.
#include <stdio.h>
void func(char * p);

int main(void)
{
char * p = "abcdefg";
printf("%s\n", p);
func(p);

return 0;
}

void func(char * p)
{
*(p + 2) = 'z';
printf("%s\n", p);
}

This "seems" to work. The string literal is modified. Is this
undefined behaviour?


Yes, it is undefined behaviour.
If so, can I take advantage of it if the
code runs only on platform x with implementation y? That is, is
the behaviour consistent for a particular platform and
implementation, albeit undefined?


Undefined means that it is undefined. Therefor anything can happen,
including it doing exactly what you expect unless you run it on a Sunday
in which case it invokes the Wrath Of God and you get struck by
lightning.

In other words, don't do that.
--
Flash Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spamtrap, it is real and I read it.
Nov 14 '05 #24

P: n/a
Flash Gordon wrote:
Therefor anything can happen,
including it doing exactly what you expect unless you run it on a Sunday
in which case it invokes the Wrath Of God and you get struck by
lightning.


It would have to be on a Saturday. I'm Jewish.

EM
Nov 14 '05 #25

P: n/a
On 17 Dec 2003 00:16:08 GMT, in comp.lang.c , Alex
<al*******@hotmail.com> wrote:
Mark McIntyre <ma**********@spamcop.net> wrote:
On 16 Dec 2003 23:35:20 GMT, in comp.lang.c , Peteris Krumins
<pk****************@inbox.lv> wrote:

char const *p = "some string";
const pointer to char


Nope, it is equivalent to the first example. Const pointer
to char would be:

char * const p;


oops, you're right. My mistake. I expect Dan P has heaped contumely on
me in another thread... too bad.
char const * const p = "some string";

syntax error


Nope. Again, as above, const pointer to const char.


Again you could be right - my compiler barfed at it, possibly because
its an abhomination...

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #26

P: n/a
Mark McIntyre wrote:
.... snip ...
oops, you're right. My mistake. I expect Dan P has heaped contumely
on me in another thread... too bad.


Not yet. Maybe he is ill, or there was a comms glitch :-)

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #27

P: n/a
Christopher Benson-Manica wrote:
glen herrmannsfeldt <ga*@ugcs.caltech.edu> spoke thus:
For compatibility with K&R C it has to be allowed. I know some
compilers have it as an option. Others may not have the
compatibility mode anymore.

K&R2, p194:
"...the behavior of a program that attempts to alter a string
literal is undefined." I assume by K&R C you're speaking of pre-ANSI...?


Maybe it should be called K&R1 to avoid confusion.

Yes, pre-ANSI.

-- glen

Nov 14 '05 #28

This discussion thread is closed

Replies have been disabled for this discussion.