Home > Back-end >  Different address while duplicating string literal
Different address while duplicating string literal

Time:03-16

I am new to programming.
Why does printf("%d","Kurukshetra"); and printf(" %d",ar); returns different memory address although they are pointing to the first character of the string

#include <stdio.h>
int main()
{
    char ar[]="Kurukshetra";
    printf("%d","Kurukshetra");
    printf(" %d",ar);
    printf(" %s",(ar 1));
    printf(" %s ","Kurukshetra" 1);
return 0;
}

CodePudding user response:

First of all using the conversion specifier %d with pointers is invalid.

Instead of

printf("%d","Kurukshetra"); 

and

printf(" %d",ar);

you have to write

printf("%p\n", ( void * )"Kurukshetra"); 

and

printf( "%p\n", ( void * )ar);

The array ar and the string literal occupy different extents of memory. So their addresses are different.

The array ar was initialized by characters of the string literal by means of copying them in the extent of memory occupied by the array.

char ar[]="Kurukshetra";

You may imagine this the following way

char string_literal[] = "Kurukshetra";
char ar[sizeof( string_literal )];

memcpy( ar, string_literal, sizeof( string_literal ) );

As you see each array has its one extent of memory.

Also pay attention to that even identical string literals can have different addresses. That is the compiler can store identical string literals as one character array with static storage duration or as separate arrays. This depends on compiler options.

So for example if the compiler stores identical string literals as separate arrays then these calls

printf("%p\n", ( void * )"Kurukshetra"); 
printf("%p\n", ( void * )"Kurukshetra"); 

can produce different values.

Form the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined

CodePudding user response:

char ar[]="Kurukshetra";
printf("%d","Kurukshetra");
printf(" %d",ar);

First of all, printing a pointer should be done using "%p". If you instrument printf to print a pointer using "%d", it is undefined behavior.

Quoting ISO/IEC 9899:1999 6.4.5 String literals

It is unspecified whether these arrays are distinct provided their elements have the appropriate values.

So, supposing you had written

char ar[]="Kurukshetra";
printf("%p","Kurukshetra");
printf(" %p",ar);

it is unspecified behavior whether the 2 pointer values are or not the same. unspecified behavior means:

behavior where this International Standard provides two or more possibilities and imposes no further requirements on which is chosen in any instance

The annex J.1 Unspecified behavior from the Portability issues of the International Standard summarizes all the cases. For string literals it says:

  • Whether two string literals result in distinct arrays (6.4.5).
  • Related