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 27 2034
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
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
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.
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.
"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
"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
"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 :)
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)
"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.
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
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 =---
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
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)
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.
"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>
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
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.
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
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
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?
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
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)
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.
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
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 =---
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!
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: David Opstad |
last post by:
I have a question about text rendering I'm hoping someone here can
answer. Is there a way of doing linguistically correct rendering of
Unicode strings in Python? In simple cases like Latin or...
|
by: Sarah Tegtmeier |
last post by:
Hi
I have a question about the correct use of the attribute
xsi:schemaLocation. My programm has to process XML files where the value of
this attribute causes some problems. The programm is...
|
by: Richard Golebiowski |
last post by:
I have been trying to figure this out for quite some time and cannot
find any examples in VB.Net or in VB that work correctly. I am working
on an application where I want the user to be able to...
|
by: john.burton.email |
last post by:
I've done some extensive searching and can't seem to find an answer to
this -
Is it correct to using "using" with templates, for example:
using std::vector;
Or do I need to specify the type...
|
by: Rob Thorpe |
last post by:
Given the code:-
r = sscanf (s, "%lf", x);
What is the correct output if the string s is simply "-" ?
If "-" is considered the beginning of a number, that has been
cut-short then the...
|
by: blackg |
last post by:
Input string not in correct format
--------------------------------------------------------------------------------
I am trying to view a picture from a table. I am getting this error
Input string...
|
by: thisis |
last post by:
Hi All,
I need the PUBS.mdb for pulling images:
PUBS.mdb must have the table: pub_info
tbl_pub_info : has 3 fields
Data_Type : ok
Data_Type : ok
|
by: sehguh |
last post by:
Hiya Folks,
I am Currently using windows xp. Also using Visual Web Developer 2005 and Microsoft Sql server 2005.
The main page consists of an aspx page and a master page.
The page also...
|
by: lee123 |
last post by:
I have a problem getting the correct to count +1 every time I get an answer right
and the incorrect is the same.
I have two lbl's named number1 and number2 which produces a Rnd# in each lbl.
...
|
by: onetruelove |
last post by:
I want to creat a post like this blog:
http://onlinetoefltest.blogspot.com/2007/08/level-c-lesson-1.html
When you chose all the answers and click show answer a msg box will appear and tells how...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
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...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
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,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
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,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |