2

I'm studying strings and pointers in C. From what I have studied, I understand that if I write:

char * s = "hello";

I am creating a 6 character / 6 byte array and making char * s point to this newly created array In the example above I create two strings a and b:

char a [20];
char b [20];

and then two pointers s and s2 pointing to a and b:

char * s = a;
char * s2 = b;

If I write:

if (s == s2)

I get printed False on screen, because, ACCORDING TO MY LOGIC, I am comparing if email pointed to by s is equal to what s2 is pointing to. So far I have understood everything. Now the part that I didn't understand. If instead of creating two strings and assigning addresses to pointers, I wrote:

char * s = "hello";
char * s2 = "hello";
if (s == s2)

I am printed True. I don't understand why. This second conditional statement shouldn't compare whether to use is pointed by s equal to what s2 is pointing to? I expected False to be printed again. Help !!

#include <stdio.h>
#include <stdlib.h>

int main()
{
    {
        char a[20] = "hello";
        char b[20] = "hello";
        char *s = a;
        char *s2 = b;

        if(s == s2)//address of s == address of s2 ? False
        {
           printf("True\n");
        } 
        else
        {
           printf("False\n");
        }
    }

    //if i try to do :

    char *s = "hello";
    char *s2 = "hello";

    if(s == s2)//the result is True, but i don't understood because.
    { 
       printf("True\n");
    }
    else
    {
       printf("False\n");
    }
    return 0;
}
  • 3
    `a` and `b` have probably been optimized by your compiler to point to 1 piece of memory – byxor Nov 24 '20 at 14:45
  • 2
    Identical string literals might or might not be the same literal in the memory. You can't rely on either behavior. – Eugene Sh. Nov 24 '20 at 14:46
  • 1
    Identical string literals are very commonly optimized by the compiler to only get stored in one single location, something called "string pooling". (gcc `-fmerge-constants` (default) vs `-fno-merge-constants` if I remember correctly) – Lundin Nov 24 '20 at 14:48
  • 1
    Multiple occurrences of a string literal *may* map to a single instance in memory. – John Bode Nov 24 '20 at 14:49
  • Hei guys then, after the instructions: char * s = "hello"; char * s2 = "hello"; Istruction: if (s == s2) it is comparing memory addresses that are most likely identical because the compiler has made s and s2 point to the same memory area. Am I right? – Antonio Pio Mennuni Nov 24 '20 at 14:57

0 Answers0