簡體   English   中英

訪問指針數組中的數組

[英]Accessing arrays in an array of pointers

假設我在C中有一個指針數組。例如:

char** strings

數組中的每個指針都指向不同長度的字符串。 如果我願意,例如: strings + 2 ,盡管長度可能有所不同,但我會到達第三個字符串嗎?

是的,您將(假設數組已正確填充)。 將雙指針情況想象成一個表。 然后,您將具有以下內容,其中每個字符串位於一個完全不同的內存地址。 請注意,所有地址都是偽造的,可能在任何系統中都不是真實的。

strings[0] = 0x1000000
strings[1] = 0xF0;
...
strings[n] = 0x5607;

0x1000000 -> "Hello"
0xF0 -> "World"

請注意,這里沒有任何實際的文本存儲在字符串中。 這些地址上的存儲將包含實際的文本。

因此, strings + 2將在strings指針上添加兩個,這將產生strings[2] ,這將產生一個內存地址,該地址可用於訪問字符串。

strings + 2string指向的緩沖區的第三個元素的地址。
*(strings + 2)strings[2]是第三個元素,它也是指向字符緩沖區的指針。

我認為您正在尋求通過表達方式來訪問第三個元素

strings[2];

但這不是事實,因為看一下表達式string[2]的類型

Type is char *

按照標准

A 'n' element array of type 't' will be decayed into pointer of type __t__.With the exception when expression is an operand to '&' operator and 'sizeof' operator.

所以strings [2]等效於*(strings + 2),所以它將在第三位置打印pointer to pointer的內容,即pointer的內容,即地址。

strings+2;

類型為char **將打印3 rd location's address,ie,address of the 3rd element of array of pointer, whose base address is stored in **string.

但是在您的問題中,您沒有顯示對char ** strings任何分配,我通過假設它使用特定的指針數組進行初始化來回答。
根據您的問題,這樣做很愚蠢

*(strings + 2)

由於尚未初始化。

暫無
暫無

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

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