char str[] = "string";
sizeof(str) 的值为7。
char *str = "string";
sizeof(str)的值为4(指针的大小)。
这两者的区别是什么? 为什么会这样?下面是别的地方看到的讨论,看完后就明白了。
===============================分====================================
The two declarations are not the same.
char ptr[] = "string";
declares a char array of size 7
and initializes it with the characters
s
,t
,r
,i
,n
,g
and \0
. You are allowed to modify the contents of this array.
char *ptr = "string";
declares ptr
as a char pointer and initializes it with address of string literal"string"
which is read-only. Modifying a string literal is an undefined behavior. What you saw(seg fault) is one manifestation of the undefined behavior.
========================================================
And a sizeof(ptr) will give different results to for the different declarations. The first one will return the length of the array including the terminating null character. The second will return the length of a pointer, usually 4 or 8.
It's also true in the second place that the contents of ptr can be changed. But the contents are the pointer to the literal, not the characters.
+1, great answer. It is also true and important to understand that with char *ptr = "string"; the ptrcan be pointed at something else and can therefor be 'changed' in what it is pointing at but the characters"string" is a literal and cannot change.
It would also be worth mentioning the performance issues. Declaring an initialized automatic array variable will fill the entire array contents every time the variable comes into scope. Declaring an initialized automatic pointer variable will simply assign the pointer (a single word write) when the variable comes into scope. If the string is long or the block is entered often (like each iteration of a loop), the difference could be very significant!
@AmigableClarkKant, actually, sizeof(ptr) is not the length of the array unless ptr is declared as a char array. If ptr is defined as an int arryay with 3 elements, sizeof(ptr) will return the sum ofsizeof(int) of each element.
原文地址:http://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string