2016-09-10 38 views
2
#include <stdio.h> 

struct Analysis { 
    int lnlen; 
    int arr[2]; 
    char* name; 
}; 

int main() 
{ 
    struct Analysis ana_space[2]; 
    char *ptr = (void*) &ana_space; 

    ana_space[0].lnlen = 0; 
    ana_space[0].arr[0] = 1; 
    ana_space[0].arr[1] = 2; 
    ana_space[0].name = "Peter"; 

    printf("\n%d\n", *ptr);  // print 0; 

    *ptr = 10;     // how to use memcpy here; 

    printf("\n%d\n", *ptr);  // print 10; 

    ptr = ptr + sizeof(int); // advance pointer by int; 

    printf("\n%d\n", *ptr);  // print 1; 

    ptr = ptr + 2*sizeof(int); // advance pointer by 2 ints; 

    printf("\n%s\n", *ptr);  // print "Peter"; --------------not work 

    //*ptr = "Jim";    // how to assign new name "Jim" into that memory; 
    return 0; 
} 

輸出:如何將字符串分配到char *指針?

(空)

我想使用的char *作爲指針去通過存儲器地址獲取一些數據並將值存儲到m中埃默裏。

對於int和int數組,它工作正常,但不適用於字符串。

如何打印字符串並將新的字符串值存儲到內存中?

+1

你爲什麼不使用。運算符將值存儲到成員中?你是否知道你在做什麼的問題? – 2501

+2

你沒有考慮結構內的填充。 – Dmitri

+0

第1步:打開編譯器警告以快速捕獲像'printf(「\ n%s \ n」,* ptr)等問題。 – chux

回答

1

你的做法是不可移植。最好使用offsetof以確保您可以可靠地指向struct的成員的地址。

int main() 
{ 
    struct Analysis ana_space[2]; 
    char *ptr = (void*) &ana_space; 

    size_t offset1 = offsetof(struct Analysis, arr); 
    size_t offset2 = offsetof(struct Analysis, name); 

    ana_space[0].lnlen = 0; 
    ana_space[0].arr[0] = 1; 
    ana_space[0].arr[1] = 2; 
    ana_space[0].name = "Peter"; 

    // advance pointer to point to arr. 
    ptr = ptr + offset1; 

    // advance pointer to point to name 
    ptr = ptr + (offset2-offset1); 

    // Cast the pointer appropriately before dereferencing. 
    printf("\n%s\n", *(char**)ptr); 

    // how to assign new name "Jim" into that memory; 
    *(char**)ptr = "Jim"; 
    printf("\n%s\n", *(char**)ptr); 

    return 0; 
} 

您使用的:

printf("\n%d\n", *ptr);  // print 0; 

*ptr = 10;     // how to use memcpy here; 

printf("\n%d\n", *ptr);  // print 10; 

和預期輸出是有缺陷的。它只適用於小端系統。我建議使用:

printf("\n%d\n", *(int*)ptr); 

*(int*)ptr = 10; 

printf("\n%d\n", *(int*)ptr); 
1

您提交的代碼可能會導致未定義的行爲,因爲填充和類型表示(實現定義)。

後您增加指針PTR這裏:

ptr = ptr + 2*sizeof(int); 

指針ptr指向的結構分析的成員名稱。如果取消引用指針ptr,則會得到char類型,因此只有一個字節。該字節不表示指向字符串的指針。

指針ptr必須轉換爲指向char的指針的類型指針,然後解除引用,以便獲取成員名稱的正確值和完整值。

結果值是一個指向字符串"Peter"的指針。

+0

'ptr'可能不一定指向'struct'的'name'的地址。這取決於成員之間是否有填充。 –

+0

@RSahu顯然。 – 2501

+0

ANSI C的stddef.h中的offsetof()宏可以幫助避免任何有關填充的猜測工作。 –

1

ANSI C在stddef.h中有一個名爲offsetof()的宏,它提供了一種計算結構中成員的指針偏移的更確定的方法。在這裏,我們可以直接在ana_space [0]中獲得名稱成員的地址。

ptr = (char*) &ana_space + offsetof(struct Analysis, name); 

這將取消任何有關填充的猜測工作。

這個指針則必須適當地轉換爲打印的名字的內容:

printf("%s\n", *(char**) ptr);