簡體   English   中英

將 int 數組轉換為 c 中的 char 指針

[英]Casting an int array into a char pointer in c

我在 C 中運行了這幾行代碼:

int tab[]={4,6,8,9,20};
char *p;     
p=(char*)tab

問題是如何使用指針 p 打印 20 的值。

所以我使用了一個for循環來查看p發生了什么

    for(int i=0;i<20;i++){
        printf("%d ",p[i]);
    }

我得到了這個 output:

4 0 0 0 6 0 0 0 8 0 0 0 9 0 0 0 20 0 0 0

我想了解那些出現的零背后的邏輯。

您幾乎可以肯定使用的是int為 4 個字節的體系結構,以及首先存儲“最小”字節的小端體系結構。

所以int4存儲為:

+----+----+----+----+
|  4 |  0 |  0 |  0 |
+----+----+----+----+

int20存儲為:

+----+----+----+----+
| 20 |  0 |  0 |  0 |
+----+----+----+----+

memory 中的整個數組如下所示:

+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
|  4 |  0 |  0 |  0 |  6 |  0 |  0 |  0 |  8 |  0 |  0 |  0 |  9 |  0 |  0 |  0 | 20 |  0 |  0 |  0 |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+

現在,當您將這 20 個字節作為字符進行迭代(因此一次一個字節)時,結果應該不再令人驚訝了。

在您的機器上, sizeofint4char sizeof大小根據定義為1

因此,對於p ,您將逐字節打印一個int


“問題是如何使用指針 p 打印 20 的值。”


至於那個:

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

int main(void) 
{
     int tab[] = {4, 6, 8, 9, 20};
     char *p = 0;     
     
     /* The type that & returns is a 
     *  pointer type, in this case, a 
     *  pointer to the 4th element of 
     *  the array.
     */
     p = (char*) &tab[4];
     
     /* As %d expects an int, we cast 
     *  p to an int *, and then 
     *  dereference it. 
     */
     printf("%d\n", *(int *)p);
     return EXIT_SUCCESS;
}

Output:

20

編輯:上面的代碼依賴字節序。

暫無
暫無

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

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