2012-11-08 27 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 *)确定指针的大小,而不是依靠硬编码的,不可靠的假设。