Question about pointers and strings in C

Possible duplicate:
What is the difference between char s [] and char * s in C?
Difference between char * str = "..." and char str [N] = "..."?

I have a code that puzzled me.

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

int main(int argc, char *argv[])
{
  char* string1 = "this is a test";
  char string2[] = "this is a test";
  printf("%i, %i\n", sizeof(string1), sizeof(string2));
  system("PAUSE"); 
  return 0;
}

When it prints the size of string1, it prints 4, which is to be expected since the size of the pointer is 4 bytes. But when it prints string2, it prints 15. I thought the array was a pointer, so the size of string2 should be the same as string1, right? So why does it print two different sizes for the same data type (pointer)?

+5
source share
7 answers

- . , , .

(n1256):

6.3.2.1 Lvalues,
...
3 , sizeof & , , , " type", " type", lvalue. , undefined.

" " 15- char.


    char *string1 = "this is a test";

string1 char. " " char [15] char *, string1.





    char string2[] = "this is a test";


- . :

6.7.8
...
14 , . ( , ) .
...
22 , . .

string2 char, , .

, , :

Item          Address       0x00  0x01  0x02  0x03
----          -------       ----  ----  ----  ----
no name       0x08001230    't'   'h'   'i'   's'
              0x08001234    ' '   'i'   's'   ' '
              0x08001238    'a'   ' '   't'   'e'
              0x0800123C    's'   't'    0
              ...
string1       0x12340000    0x08  0x00  0x12  0x30
string2       0x12340004    't'   'h'   'i'   's'
              0x12340008    ' '   'i'   's'   ' '
              0x1234000C    'a'   ' '   't'   'e'
              0x1234000F    's'   't'    0

; , . undefined; , . , .

string1 string2, .

, string1, , . string2, , .

string2 , sizeof ( ) .

%i size_t. C99, %zu. C89 %lu unsigned long:


C89: printf("%lu, %lu\n", (unsigned long) sizeof string1, (unsigned long) sizeof string2);
C99: printf("%zu, %zu\n", sizeof string1, sizeof string2);

, sizeof - , ; , , ( ).

+5

. : , .. - - , , sizeof, .

+13

string1 , string2 .

int a[] = { 1, 2, 3};, a -3 ( ).

string2 15, nul-terminated ( 15 - + 1).

+4

sizeof. sizeof, sizeof , . , string2 , C - . ( - , .) ( !) sizeof, C.

sizeof.

+4

, test2 - , (14 ). , sizeof - , .

+2

. - , , - .

+1

  • string1 , .
  • string2 - , .

C- iterprets 2 -. http://c-faq.com/aryptr/aryptr2.html.

+1

All Articles