gpt4 book ai didi

C 编程,关于指针的困惑

转载 作者:行者123 更新时间:2023-11-30 21:30:41 25 4
gpt4 key购买 nike

我有以下代码

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com