-1

I was searching about this code that I didn't believe that works, but I found something in books about table of strings that exists in compiler.

char *p;
p = "something";

printf("%s", p);

How this code works ?

ViniciusArruda
  • 970
  • 12
  • 27
  • 2
    First you should read about C-pointers. If you are used to them, maybe you should reword the question if it isn't then clear to you already. – dhein Nov 19 '14 at 13:36
  • `p` points to the string "something" and `printf` prints the string. That's how things work in C, you should read a book about C, pointer, strings and/or follow a tutorial. – Jabberwocky Nov 19 '14 at 13:39

2 Answers2

4

"something" is a string literal, which is a null-terminated character array that is stored in read-only memory. p is a pointer to char. Since you set this pointer to point at read-only memory, you should always declare it as const char*.

sizeof(p) gives the size of p. p is a pointer so you get the size of a pointer, 4 bytes on your specific system.

Had you instead declared an array char arr[] = "something"; you would have gotten a copy of something stored in your local array, where you can also modify it. And if you take sizeof an array, you get the expected size. In the array case sizeof(arr) would give you 9+1=10 bytes.

For reference, please read:

What is the difference between char s[] and char *s?

Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • I read the reference that you showed. So, the string literal `"something"` is in read-only memory (the program allocates memory for it ? i.e. 9+1 bytes ?) and a pointer to char `p` is in the read-write memory ? It was what I read in http://en.wikipedia.org/wiki/Data_segment#Data – ViniciusArruda Nov 28 '14 at 13:37
1
char *p = "something";

This is read only so you are able to print it.

sizeof(p);

You are printing the sizeof pointer not the size of the string.

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • @X0R40 Read this link you will be able to understand what happens http://stackoverflow.com/questions/2589949/c-string-literals-where-do-they-go – Gopi Nov 19 '14 at 13:42