C 编程,关于指针的困惑

标签 c pointers

我有以下代码

char buffer[1024];  
void *temp= (void *)(buffer + 4);
int *size= (int *)temp;

我相信第三行可以通过将 temp 更改为 buffer 来简化。 我认为以下其中一项是正确的,但两者都给了我一个错误(段错误)。

int *size = (int *)(buffer + 4)

int *size = (int *)*(buffer + 4)

正确答案是什么?指针快要死了。

最佳答案

运行此代码,没有段错误。评论和打印输出将提供一些代表性。

int main (void)
{
 char buffer[11] = {'f', 'e', 'e', 'd', 't', 'h', 'e', 'b', 'a', 'b', 'e'} ;


 printf("Buffer's address in the memory:0x%x\n", buffer); //all three are the same
 printf("Buffer's address in the memory:0x%x\n", & buffer); //all three are the same
 printf("Buffer's address in the memory:0x%x\n", & buffer[0]); //all three are the same

 unsigned char a;
 for (a=0;a<11;a++)
  printf( "%c", buffer[a]);


 void *temp= (void *)(buffer + 4);
 int * size= (int *)temp;

 printf ("\ntemp:0x%x\n", temp);
 printf ("size:0x%x\n", size);
 printf ("size:%c\n", *size); 

 size    = (int *)(buffer + 4);




 printf ("\n(int *)*(buffer + 4): 0x%x\n",(int *)*(buffer + 4));
 size  = *(char *)(buffer + 4);
 printf("size:%c\n",size); // 't''s ASCII code
 printf("size:0x%x\n",size); // 't'
}

关于C 编程,关于指针的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592047/

相关文章:

c - 使用 XCode 构建、分析、编辑 unix\linux 控制台程序

c - 在 core_cm4.h 上,为什么会有类似 ((uint32_t)(int32_t)IRQn) 的转换?

c - 仅打印出所需长度的指针

list - 如何制作一个新列表指向其他地方,Lisp

c - 理解inotify示例中的对齐语句

c - 单程飞行问题

C - 结构和用户变量共享相同的内存 - 可能吗?

c - 在 C 中使用指向函数的指针调用函数

c++ - 单行指针操作

无法访问结构体中的结构体数组中的成员变量