c - 将整数解释为指向动态字符串的指针,从指向指针的指针指向的动态 block

标签 c string pointers dynamic casting

我说的有道理吗?这就是我想要做的:

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?

我不确定我还能描述什么。

最佳答案

它在 32 位环境中运行良好。然而@Blagovest Buyukliev 是正确的,你不应该对指针的大小做出假设(即使它看起来有效)。您最好将那些 unsigned int 更改为 char*´s。请参阅下面稍作修改的版本:

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() 来查看字符串。

关于c - 将整数解释为指向动态字符串的指针,从指向指针的指针指向的动态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13296228/

相关文章:

c - 设备驱动程序 : how do I get programmatic access to the actual pins/hardware?

java - 如何让程序在连字符后打印单词的反面?

c++ - dynamic_pointer_cast 的模板参数

c - 指针混淆 - 错误 : passing argument 1 of ‘value’ from incompatible pointer type; note: expected ‘...’ but argument is of type ‘...'

c - 如何设置字符串类型的结构成员

c - 如何检查列表中的下一个元素是否超出范围?

c - 如何在 ARM Cortex M4 TM4C123G 微 Controller 中使用 GPIO 端口控制 (GPIOPCTL)?

c - 如何在 C 中使用 libxml 检查 DTD?

javascript - 使用javascript从字符串中提取数字

c# - 子串深度扫描