![]() |
| | #1 |
| Registered User Join Date: Aug 2008
Posts: 1
| 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;
}
|
| explorecpp is offline | |
| | #2 |
| and the Hat of Guessing 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 | |
| | #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 | |
| | #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 | |
| | #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 | |
![]() |
| Tags |
| const |
| Thread Tools | |
| Display Modes | |
|
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 |