string initialization

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • zhanghongqi
    New Member
    • Oct 2007
    • 1

    string initialization

    Hi, all

    What is the difference of following char initializations .
    char *p="Hello";
    char p[]="Hello";
  • Meetee
    Recognized Expert Contributor
    • Dec 2006
    • 928

    #2
    Originally posted by zhanghongqi
    Hi, all

    What is the difference of following char initializations .
    char *p="Hello";
    char p[]="Hello";
    Hi,

    In the first case if *p is assigned to some other value the allocate memory can change, where as in the second case 5 bytes are allocated to the variable p which is fixed.

    Regards

    Comment

    • oler1s
      Recognized Expert Contributor
      • Aug 2007
      • 671

      #3
      Let me clarify. The first method gets you a pointer to a constant literal. You can't modify it. Well, you could always point p to something else, but then you lose the reference to the string literal.

      The second method gets you an actual character array, and then initializes it.

      Comment

      • mattmao
        New Member
        • Aug 2007
        • 121

        #4
        I reckon the difference is: with the first option you allocate new memory every time you modify the content, whereas with the second option, you allocate the memory address once and then only change the content start from that address.
        Code:
        #include <stdio.h>
        
        int main()
        {
            char *array1="ABCDEFG";
            char array2[]="ABCDEFG";
            int i;
        
            
            printf("array1 contains:%s\n", array1);
            printf("array2 contains:%s\n", array2);
        
            array1="XXXXXXX";
        
            for(i=0; i<7; i++)
            {
                array2[i]='X';
            }
        
            printf("array1 contains:%s\n", array1);
            printf("array2 contains:%s\n", array2);
        
            return 0;
        }
        Here is the result:
        Code:
        Mattmao@(dspp) 181$gcc arrays.c
        Mattmao@(dspp) 182$./a.exe
        array1 contains:ABCDEFG
        array2 contains:ABCDEFG
        array1 contains:XXXXXXX
        array2 contains:XXXXXXX
        Mattmao@(dspp) 183$

        Comment

        Working...