#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2

    Concerning addresses of pointers, arrays and string literals


    I never seem to run out of questions for these guys.

    I did two experiments and came up with a hypothesis; please tell me if it's correct.

    The experiment was to compare the output of the following two programs:

    Code:
    #include <stdio.h>
    
    int main()
    {
        char a[] = "hi!", b[] = "hi!";
        char *p1, *p2;
        p1 = a;
        p2 = b;
        printf("value of p1: %p\n", p1);
        printf("value of p1: %p\n", p2);
    }
    Code:
    #include <stdio.h>
    
    int main()
    {
        char *p1, *p2;
        p1 = "hi!";
        p2 = "hi!";
        printf("value of p1: %p\n", p1);
        printf("value of p1: %p\n", p2);
    }
    for the first, I got different values for p1 and p2.
    for the second, I got the same.

    from this I concluded that the computer makes only one "inner string" for a string literal, and reuses it if there is a declaration for the same string.

    the reason why values were not the same in the first case is because p1 and p2 point to arrays, not string literals.
    it just so happens that arrays a and b are initialized to the same string.

    am I correct?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,379
    Rep Power
    1871
    That's pretty much correct.

    However, you should know that merging duplicate strings is an optimisation, and not a guarantee.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo