473,385 Members | 1,942 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,385 software developers and data experts.

why does this pointer work?

this works

char *p ;

p="xat";

cout << p <<endl;

i thought you need something like this

char *p=new char[10];
May 29 '06 #1
14 2390
"jagguy" <jo**********@optusnet.com.au> wrote in message
news:44**********************@news.optusnet.com.au ...
this works

char *p ;

p="xat";
"xat" is a constant char array and p now points to it.
cout << p <<endl;

i thought you need something like this

char *p=new char[10];

May 29 '06 #2

"jagguy" <jo**********@optusnet.com.au> wrote in message
news:44**********************@news.optusnet.com.au ...
this works

char *p ;

p="xat";

cout << p <<endl;

i thought you need something like this

char *p=new char[10];


Sure it works. It equilant to this code

const char *str = "xat";
char *p = (char *)str;
cout << p << endl;

When the compiler generates the assembly
"xat" goes into the data segment as a const.with some address
when you do p = "xat" the compiler just set the address pointed by p to the
address of "xat" in the data segment.

//eric
May 29 '06 #3

char *p ;

p="xbbat";

cout << p <<endl;


i thought you need something like this

char *p=new char[10];


Sure it works. It equilant to this code

const char *str = "xat";
char *p = (char *)str;
cout << p << endl;

When the compiler generates the assembly
"xat" goes into the data segment as a const.with some address
when you do p = "xat" the compiler just set the address pointed by p to
the address of "xat" in the data segment.

//eric

if it is a constant then this shouldn't work but it odes

char *p ;

p="xbbat";

cout << p <<endl;

p="xbbat";

cout << p <<endl;
May 29 '06 #4

"Eric Jensen" <er**@no.spam.com> wrote in message
news:44***********************@dread16.news.tele.d k...

"jagguy" <jo**********@optusnet.com.au> wrote in message
news:44**********************@news.optusnet.com.au ...
this works

char *p ;

p="xat";

cout << p <<endl;

i thought you need something like this

char *p=new char[10];


Sure it works. It equilant to this code

const char *str = "xat";
char *p = (char *)str;
cout << p << endl;

When the compiler generates the assembly
"xat" goes into the data segment as a const.with some address
when you do p = "xat" the compiler just set the address pointed by p to
the address of "xat" in the data segment.

//eric


if it is a constant then this shouldn't work but it odes

char *p ;

p="xbbat";

cout << p <<endl;

p="xbbat";

cout << p <<endl;
May 29 '06 #5

"jagguy" <jo**********@optusnet.com.au> wrote in message
news:44***********************@news.optusnet.com.a u...
if it is a constant then this shouldn't work but it odes

char *p ;

p="xbbat";

cout << p <<endl;

p="xbbat";

cout << p <<endl;


char *p; // <- this is just a pointer. it points to a location in memory

"xbbat" is a string literal, located inside the binary (.exe).
When you run your program it's loaded into memory.
you assignments will only set the value of the pointer p to point at the
area in memory that contains the string "xbbat" (wich is loaded into memory
with the program when executed).

char *p;
p = "string";

You do not assign the value "string" to p.
You do only set the value of p to the address in memory where the first char
of "string" is located.

However, you should not do what your doing.

It would make more sense to write:
const char *p = "sometext";
std::cout << p << std::endl;

witch is basicly the same as what you do.

//eric
May 29 '06 #6
jagguy wrote:
this works

char *p ;

p="xat";

cout << p <<endl;

i thought you need something like this

char *p=new char[10];


An analogue to your code is:

int a = 100;
int p = &a;

cout << *p;

The pointer points to a valid memory, it should work.

Ben
May 29 '06 #7
int a = 100;
int p = &a;

cout << *p;

int *p = &a;
(Although I presume it was nothing more than a typo)
-Tomás
May 29 '06 #8
jagguy posted:
this works

char *p ;

p="xat";

cout << p <<endl;

i thought you need something like this

char *p=new char[10];

You posted two separate threads, and now the replies are all over the
place.

I left you a reply in the other thread.
-Tomás
May 29 '06 #9

"jagguy" <jo**********@optusnet.com.au> skrev i meddelandet
news:44***********************@news.optusnet.com.a u...

if it is a constant then this shouldn't work but it odes

char *p ;

p="xbbat";

cout << p <<endl;

p="xbbat";

cout << p <<endl;


It is a special rule for string literals. You can assign their address
(a const pointer) to a non-const char pointer.

Originally, the C language didn't have const, so

char* p = "Hello";

has always worked this way.

Later when C++ made string literals constants, this special rule was
added to support old C code. It doesn't work for any other kind of
pointers.
Bo Persson

May 29 '06 #10
Bo Persson wrote:
Originally, the C language didn't have const, so

char* p = "Hello";

has always worked this way.

Later when C++ made string literals constants, this special rule was
added to support old C code. It doesn't work for any other kind of
pointers.


It also works with pointers to char only if you directly assign a string
literal to it.

May 29 '06 #11
jagguy wrote:
if it is a constant then this shouldn't work but it odes

char *p ;
p="xbbat";
cout << p <<endl;
p="xbbat";
cout << p <<endl;


Which line are you saying shouldn't work? If you think that you
shouldn't be able to put the address of a static string constant into a
variable of type char*, see Bo's post about the historically-derived
exception for this case. However, based on the code snippet you
posted, I surmise that perhaps you're confused as to the different
kinds of constness, and what exactly is and isn't const in this case.

First of all, make sure you know the difference (or lack thereof)
between these types:
- char *
- const char *
- char const *
- char * const
- char const * const
- const char * const
The FAQ at
http://www.parashift.com/c++-faq-lit....html#faq-18.5
should help with this. Note that some of the above are equivalent.

In light of these distinctions, the snippet you posted should work fine
because the string literal is (in terms of operator=()) char const*
const, and p is of type char *. Ordinarily you can't assign from char
const* const to char *, but there's an exception for string literals,
as was mentioned. The second assignment statement, which I guess is
what you thought shouldn't work because of constness, is fine because
the left-hand side (p) is a non-const type: char*. The fact that you
once assigned to it from a const value doesn't change that -- const has
an infectuousness to it, but it doesn't work that way.

Luke

May 30 '06 #12
Tomás wrote:
int a = 100;
int p = &a;

cout << *p;

int *p = &a;


This is right.


(Although I presume it was nothing more than a typo)
Sorry for not checking thoroughly.


-Tomás


Ben
May 30 '06 #13
benben posted:

(Although I presume it was nothing more than a typo)


Sorry for not checking thoroughly.

We all make typos. (The humans among us in anyway!).
Thankfully I copped it though before I replied, as I had already written a
lengthly post about why you needed:
int *p = reinterpret_cast<int*>( 56 );
And subsequently about how your code exhibited Undefined Behaviour.

-Tomás
May 30 '06 #14

jagguy wrote:
this works

char *p ;

p="xat";

cout << p <<endl;


It works but IMHO it shouldn't. "xat" is a constant character array
that can be assigned to a char*. Unfortunately it can be without a
const_cast. As a constant array of characters I think that is a bad
thing...assigning "xat" to p shouldn't work as p is not a pointer to
constant memory yet "xat" lives in constant memory.

I much prefer the use of a constant pointer for this operation:

const char *msg = 0;

switch (err)
{
case X: msg = "error X"; break;
case Y: msg = "error Y"; break;
}

cout << msg;

The good thing about using const char* instead of char* is that any
attempt to modify the memory pointed to by msg will result in a
compiler error. Without that const qualifier an attempt to modify this
memory will compile and will result in undefined behavior when run.
This particular type of undefined behavior is especially irritating as
it quite often does wierd and unpredictable things. The term
"undefined behavior" would indicate this as the normal situation but
actually undefined behavior is quite often very predictable and easy to
find the culprit of...this one can be very difficult and unpredictable
even with a specific compiler.

May 30 '06 #15

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

Similar topics

4
by: PKH | last post by:
This is a part of an autopointer template i'm using. I originally had a Get() member that returned the pointer, but thought it would nice to be able to use the -> operator. The question is why...
3
by: Zheng Da | last post by:
Will the following class work well? If it can not work correctly in some situation, could you help me to fix it? Thank you. //the class will work like the reference in java //when you create a...
24
by: David Mathog | last post by:
If this: int i,sum; int *array; for(sum=0, i=0; i<len; i++){ sum += array; } is converted to this (never mind why for the moment):
5
by: yogesh | last post by:
Why does the following code gives an error. char c="sometext"; char **cp = &c; This gives the error "can not covert from char (*) to char**; But when i change the code to char...
5
by: mkaushik | last post by:
Hi everyone, Im just starting out with C++, and am curious to know how "delete <pointer>", knows about the number of memory locations to free. I read somewhere that delete frees up space...
7
by: Bo Yang | last post by:
Hi , I am reading some boost code now , and I got confused by the following code in the add_reference type trait . template <class TT&(* is_reference_helper1(wrap<T>) )(wrap<T>); char...
5
by: nagrik | last post by:
Hello group, Last week I picked up a thread, which pointed out that if a copy constructor is created with pointers instead of reference, there is a danger of it going in infinite recursion. ...
42
by: Sheldon | last post by:
Hi, This program works when tested with gdb ( see results 1) but when used in a larger program where 12 becomes 1500 there exists a problem when freeing the memory ( see results 2). Can anyone...
8
by: mdh | last post by:
May I ask this. Given the declaration: int myf( int, int); and a function pointer: (*fp)=int myf(int, int); where I am initializing fp to point at myf....or trying to..
19
by: Angus | last post by:
I have a socket class CTestClientSocket which I am using to simulate load testing. I create multiple instances of the client like this: for (int i = 0; i < 5; i++) { CTestClientSocket* pTemp...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
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$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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?
1
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...
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,...

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.