Thread: difference between: const char *, char *

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    5

    difference between: const char *, char *

    Can anyone tell me the difference (if any) of the following (memory wise) of using const * vs char *:

    Code:
    #include <conio.h>
    #include <stdio.h>
    
    #define GET_NUM_ELEMENTS(x) (sizeof(x) / sizeof(x[0]))
    
    int main(void)
    {
        const char *cStr = "Stuff";
        char *str = "Stuff";
    
        const char *cStrArray[] = { "Um", "Some", "Words" };
        char *strArray[] = { "Um", "Some", "Words" };
    
        for(register unsigned int i = 0; i < GET_NUM_ELEMENTS(StrArray); i++)
            printf("%s ", strArray[i]);
    
        getch();
    
        return 0;
    }
    Thanks.

  2. #2
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    const char * make the char pointed at contant, but char * makes it constant.

  3. #3
    Registered User
    Join Date
    Jul 2003
    Posts
    102
    Hi,
    I think memory wise no difference. Only this difference:
    char *p="name";
    p="newname";//possible
    *p='q';//possible
    But,
    const char *p="name";
    p="newname";//possible
    *p='q';//not possible.
    Saravanan.T.S.
    Beginner.

  4. #4
    Registered User
    Join Date
    Jun 2003
    Posts
    5
    Thanks for the fast reply.
    Not sure what chrismiceli is getting at though.

    saravanan_ts: im assuming the memory is automatically resized when:

    Code:
    p="newname"; //possible
    *p='q';	     //possible
    and there is no need for a malloc(), free() call??

    also re you sure this is possible:
    Code:
    const char *p="name";
    p = "newname"; //possible
    just thinking the compiler aint going to like changing a const

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  3. AnsiString versus char *
    By Zahl in forum C++ Programming
    Replies: 35
    Last Post: 10-16-2002, 08:38 PM
  4. Strings are V important...
    By NANO in forum C++ Programming
    Replies: 15
    Last Post: 04-14-2002, 11:57 AM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM