C指针,指向混乱 [英] C Pointer confusion
本文介绍了C指针,指向混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要存储在内存中的字符串,后来阅读:
$$ - > desc.constant-> base.id =(字符*)malloc的(200);
sprintf的($$ - > desc.constant-> base.id,%F,$ 1);
的printf( - >%S \\ n,$$ - > desc.constant-> base.id); // A线
的printf( - >%I \\ N,$$ - > desc.constant); // B线//其他一些code//然后,后来在一个函数调用:的printf(%i的,expr-> desc.constant); // D线
的printf(%S,expr-> desc.constant-> base.id); // C线
虽然B线和D线显示了相同的地址,在C线的printf的失败,分段故障。我缺少什么?
任何帮助真的会AP preciated!
解决方案
的printf( - >%I \\ N,$$ - > desc.constant); // B线
这是无效的。当你表现出线条在它之前的恒
实际上是一个指针,你不能把它当作好像它是类型 INT
。它们不necassarily具有相同的sizeof和对准。使用用于无效*
的格式。它会输出内存地址正确:
的printf( - >%P \\ N(无效*)$$ - > desc.constant); // B线
I want to store a string in memory and read it later:
$$->desc.constant->base.id = (char*)malloc(200);
sprintf($$->desc.constant->base.id, "%f", $1);
printf("->%s\n", $$->desc.constant->base.id); //LINE A
printf("->%i\n", $$->desc.constant); //LINE B
//SOME OTHER CODE
//Then, later on in a function call:
printf("%i", expr->desc.constant); // LINE D
printf("%s", expr->desc.constant->base.id); // LINE C
Although Line B and Line D show the same address, the printf in Line C fails with a Segmentation fault. What am I missing?
Any help would really be appreciated!
解决方案
printf("->%i\n", $$->desc.constant); //LINE B
That is invalid. As you show the line prior to it that constant
is actually a pointer, you cannot treat it as if it were of type int
. They don't necassarily have the same sizeof and alignment. Use the format used for void*
. It will output memory addresses properly:
printf("->%p\n", (void*)$$->desc.constant); //LINE B
这篇关于C指针,指向混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文