2012-11-08 30 views
2

我有道理嗎?這是我想要做的:將整數解釋爲指向動態字符串的指針,從指向指針的動態塊開始

unsigned int *a = 0; 
unsigned int **b = &a; 
// b -> a -> null 

*b = (unsigned int*)malloc(12); 
// b -> a -> [xxxx|xxxx|xxxx] 

*(*b+1) = (unsigned int)malloc(sizeof("come on!")); 
// b -> a -> [xxxx|xxxx|xxxx] 
//     v 
//    [xxxxxxxxx] 

strcpy((char*)*(*b+1),"come on!"); // FAILS! why? 

我不知道我還能描述什麼。

+1

你爲什麼假設指針和整數總是4個字節? –

+0

哈哈哦,男人,我忘了我正在運行一個64位系統。是的,需要8個字節的指針。哎呦!謝謝。 – Shadd

+0

這些數字有什麼問題?他們只是簡化的可視化。 – Shadd

回答

1

它在32位環境下正常工作。然而@Blagovest Buyukliev是正確的,你不應該對指針的大小作出假設(即使它看起來工作)。你會更好更改這些unsigned intchar *的。見下面略加修改:

char* *a = 0; 
char* **b = &a; 
// b -> a -> null 

*b = malloc(12); 
// b -> a -> [xxxx|xxxx|xxxx] 

*((*b)+1) = malloc(sizeof("come on!")); 
// b -> a -> [xxxx|xxxx|xxxx] 
//     v 
//    [xxxxxxxxx] 

strcpy(*((*b)+1),"come on!"); // FAILS! why? 

printf("%s", a[1]); 

這就是說,即使它的工作原理,它可能是學習指針和記憶的好方法,你應該對此事查詢語言的使用。
我添加了一個printf()來查看字符串。

+3

不僅如此,它還是未定義的行爲。即使在32位系統上,「unsigned int」的大小也不能保證爲32位。 –

0

我不知道這個計劃的真正意圖,但考慮到視覺效果,我想你理解錯了,並如下我將它改寫:

// why do you need a at all? b can be initialised to NULL without a second variable 
// unsigned int *a = NULL; 
unsigned int **b = NULL; 

// you are allocating 3 pointers here 
b = malloc(sizeof(unsigned int *) * 3); 
// b -> [xxxx|xxxx|xxxx] 

// the second pointer is made to point to newly allocated memory 
*(b + 1) = malloc(sizeof("come on!")); 
// b -> [xxxx|xxxx|xxxx] 
//   v 
//   [xxxxxxxxx] 

strcpy((char *) *(b + 1), "come on!"); 

還要注意使用sizeof(unsigned int *)確定指針的大小,而不是依靠硬編碼的,不可靠的假設。