#include <stdio.h>
#include <string.h>
int main() {
char *s[] = {"cricket","tennis","football"};
printf(" String are: \n\n");
printf(" %s \n", *(s));
printf(" %s \n", *(s+1));
printf(" %s \n", *(s+2));
printf(" \n\n");
printf(" Starting locations of the string are: \n\n");
printf(" %d\n",*(s));
printf(" %d\n",*(s+1));
printf(" %d\n",*(s+2));
printf(" \n\n");
return 0;
}
OUTPUT:
String are:
cricket
tennis
football
Starting locations of the string are:
134514112
134514120
134514127
s is a array of character pointers. s has three elements and each of them are storing the starting address of the string literals.i.e. s[0] is a pointer pointing to the starting address of "cricket". etc..
My question is :
By observing these addresses we can see that second string is stored just after the null character of the first string. All three strings are stored in sequential form. Is this always true ?
This is a linker decision - to store string literals tightly or not. There is no guaranties. Or even this may be done by compiler - it may create continuous data section that holds all involved literals. But nevertheless actual layout of that section is still implementation-specific and you shouldn't assume anything about it.
I have an example for you:
#include <stdio.h>
#include <inttypes.h>
char *s[] = { "ball", "football" };
int main( void )
{
int i;
for( i=0; i<2; i++ ) {
printf( "%" PRIuPTR "\n", (uintptr_t)s[i] );
// or printf( "%p\n", s[i] ); forr hex output
}
}
If I compile and run that program with gcc -O3
I get:
4195869
4195865
What happens here is that the optimizer merges both string literal to a single "football" so that s[0]
becomes s[1] + 4
.
That's only one example of what compiler / linker might decide on how to store string literals ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With