簡體   English   中英

為什么將指向字符串值的指針更改為另一個字符串有效,但不能直接更改字符串的值?

[英]Why does changing a pointer to a string's value to another string work, but not directly changing a string´s value?

這有效

char *pointer1="someString"; //creates a pointer to an array of chars(string) and also the string itself.
pointer1="anotherString";

但這不

char array1[]="someWords and stuff!"; //creates an array of chars(string) with 21 of size(20 for the string itself and 1 for the null character).
array1="anotherString";

為什么?

那是因為數組與指針不同,盡管數組可以隱式轉換為指針。 反之亦然。

在您的第一個示例中,指針僅指向一個字符數組。
您始終可以使指針指向不同的地址。

但是,在您的第二個示例中,您有一個數組,為了訪問該數組,您必須取消引用該數組的一個元素,這樣您就可以更改該數組。 但與指針不同的是,您不能讓數組指向不同的數組,因為它不是指針,而是實際存儲。

為了更清楚,在第一個示例中,您實際上並沒有更改數組,而是創建了一個新數組並使指針指向新數組而不是前一個數組。

char array1[]="someWords and stuff!"; //creates an array of chars(string) with 21 of size(20 for the string itself and 1 for the null character).
array1="anotherString";

這不起作用,因為數組的名稱 ( array1 ) 是第一個數組元素的地址。 換句話說,它可以被認為是一個常量指針。 聲明后,它指向一個固定地址(初始字符串的)。 然后你不能將array1指向其他地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM