C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 08-08-2008, 07:08 PM   #1
Registered User
 
Join Date: Aug 2008
Posts: 1
Question Difference between const char * and char const *

Hi,

Can any one please explain me the difference between using a const char * or a char const *. I used both in the below program and everything worked fine except for a warning when I compiled.

Code:
int main()
{
   const char *s;   //Or char const *s;
   s = (char *) malloc (10);
   strcpy(s, "abc");
   return 0;
}
Thanks in advance!!!
explorecpp is offline   Reply With Quote
Old 08-08-2008, 07:12 PM   #2
and the Hat of Guessing
 
tabstop's Avatar
 
Join Date: Nov 2007
Posts: 8,740
const char * and char const * both mean the same thing -- a pointer to chars that you cannot change (you can change the pointer, so the malloc is ok, but you CANNOT change the characters pointed to, so the strcpy is bad).
tabstop is offline   Reply With Quote
Old 08-08-2008, 11:05 PM   #3
Registered User
 
Join Date: Jun 2005
Posts: 1,343
The basic rule of thumb with const (and volatile) keyword is that it applies to whatever is immediately to its left. If there is nothing to its left, it applies to whatever is immediately to its right. The standard is a bit more specific in how it describes this, but comes essentially to the same thing.

By this logic, "const char *" is a (non-const) pointer to a const char, and "char const *" means the same thing.
grumpy is offline   Reply With Quote
Old 08-09-2008, 12:22 AM   #4
Registered User
 
Join Date: Apr 2006
Location: United States
Posts: 3,202
FYI, the warning was probably due to casting malloc's return value.

void * malloc (size_t nbytes);

There is no reason to cast the return value of malloc in C anymore because void pointers are assignable to pointers of any type.
whiteflags is offline   Reply With Quote
Old 08-09-2008, 04:48 AM   #5
Registered User
 
Join Date: Jun 2005
Posts: 1,343
Actually, the warning would be on the strcpy() call. The first argument of strcpy() is copied to, so is not a pointer to const. But you are passing a const char * as first argument .....
grumpy is offline   Reply With Quote
Reply

Tags
const

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Unkown Hang Bladactania C Programming 31 04-22-2009 09:33 AM
Seg Fault in Compare Function tytelizgal C Programming 1 10-25-2008 03:06 PM
Code review Elysia C++ Programming 71 05-13-2008 09:42 PM
Try out my new game :) ! Stan100 Game Programming 10 06-05-2003 08:10 AM
AnsiString versus char * Zahl C++ Programming 35 10-16-2002 08:38 PM


All times are GMT -6. The time now is 06:31 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22