我有以下代码
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 - C编程,关于指针的困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24592047/