我读了几个类似的问题,C: differences between char pointer and array,What is the difference between char s[] and char *s?,What is the difference between char array[] and char *array?,但似乎没有一个问题可以解释我的怀疑。
我知道
char *s = "Hello world";
使字符串不可变,而
char s[] = "Hello world";
可以修改。
我怀疑是{I} char stringA[LEN];
和char* stringB[LEN];
他们有什么不同吗?或者stringB
是否像以前的情况一样变得不可变?
答案 0 :(得分:5)
Let me give you a visual explanation:
As you can see, a
is an array of 4 characters, whereas b
is an array of 4 character pointers, each pointing to the beginning of a C string. Each one of those strings can have a different length.
答案 1 :(得分:3)
Are they any different?
Yes.
Both variables stringA
and stringB
are arrays. stringA
is an array of char
of size LEN
and stringB
is an array of char *
of size LEN
.
char
and char *
are two different types. stringA
can hold only one character string of length LEN
while elements of stingB
can point to LEN
number of strings.
Or does
stringB
again becomes immutable as in the case before?
Whether strings pointed by elements of stringB
is mutable or not will depend on how memory is allocated. If they are initialized with string literals
char* stringB[LEN] = { "Apple", "Bapple", "Capple"};
then they are immutable. In case of
for(int i = 0; i < LEN; i++)
stringB[i] = malloc(30) // Allocating 30 bytes for each element
strcpy(stringB[0], "Apple");
strcpy(stringB[1], "Bapple");
strcpy(stringB[2], "Capple");
they are mutable.
答案 2 :(得分:3)
They are not the same.
Here stringA
is an array of char
, that means printing stringA[0]
will show the letter S
:
char stringA[] = "Something";
Whereas printing stringB[0]
here will show Something
(array of pointer to char):
char* stringB[] = { "Something", "Else" };
答案 3 :(得分:2)
They are not having the same datatype, less being comparable.
char stringA[LEN];
is a char
array of LEN
length. (Array of char
s)
char* stringB[LEN];
is a char *
array of LEN
length. (Array of char
pointers)
FWIW, in case of char *s = "Hello world";
s
is a pointer which points to a string literal which is non-modifiable. The pointer itself can certainly be changed. Only the content it points to (values) cannot be changed.
答案 4 :(得分:0)
The reason
is immutable is becausechar* s = "Hello World!";
"Hello World!"
is stored in RO(Read Only) memory, sow hen you try to change it, it throws an error. Declaring it as a pointer to the first element of an "array" is NOT the reason it's immutable. You seem to be slightly confused as well. Assuming your questions is exactly what you mean,
char stringA[LEN] = "ABC";
is a string in traditional C style, but stringB
as you've defined isn't a string, it's an array of strings -
char* stringB[LEN] = {"ABC", "DEF"};
Assuming you mean what I think you mean,
char stringA[LEN] = "Hello World!"; char *stringB = malloc(LEN); strcpy(stringB, stringA);
In this case, stringB IS mutable, since it refers to writable memory.