Skip to main content
GameDev.net gamedev.net
🔒 Locked

pointer to char

Started by jagguy May 29, 2006 at 5:41 AM 3 replies 450+ views
Original Post
jagguy
jagguy
this works char *p ; p="xat"; cout << p <<endl; i thought you need something like this char *p=new char[10];
Kwak
Kwak
"xat" is a string that gets compiled as an array of chars: [x, a, t, \0]
when you say char* p="xat";, thet p is the address of the char x
the cout function prints a string that is located at address p. Note that if you compile a string "xat" that a null character (\0) automaticly is added. This means that the string ends here. If there was no null character the program would crash.
jagguy
jagguy
hi

i was doing some win32 stuff and it doesn't like string


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

char *p ;

p="xbbat";

cout << p <
p="xbbat";

cout << p <
Enigma
Enigma
Win32 is a C-API. To use std::string with a C-API you need to invoke the c_str() member function whenever you want to pass the string to a function which takes a const char * argument, i.e.:
std::string className = "MyWindowClass";std::string windowName = "My Window";CreateWindow(className.c_str(), windowName.c_str(), /*remaining parameters*/);

Use std::string.

"xat" is a contant string. It has type const char[4]. When you compile your program the executable will contain the bytes 'x', 'a', 't', and '\0', somewhere within the executable image. When you do char * p = "xat"; you are making p point to the first of those bytes within the executable image. You are also invoking a special clause in the C++ Standard which allows the conversion of a const char[] to a char *. Normally a const char[] would be converted to a const char *, but for legacy reasons C++ allows the more lenient conversion. The bytes that p points are still const however, so attempting to write to them (i.e. *p = 'c';) is undefined behaviour.

Is is only the characters themselves which are constant though, not the pointer, which is why the pointer can then be made to point to other things. If the pointer itself was const then your latest code would fail to compile:
const char * p const = "xbbat"; // both the pointer and what it points to are constcout << p << endl;p = "xbbat"; // error - a constant pointer cannot be re-bound.cout << p << endl;
Σnigma

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.