我试图让一个指针指向一个字符,然后另一个指针指向第一个指针,这使得它们都存储了相同的值。
char ch = 'A';
char *cPtr1, *cPtr2;
cPtr1 = &ch;
cPtr2 = cPtr1;
printf("cPtr1 Stored:%c Point:%x Memory:%x\n", cPtr1, *cPtr1, &cPtr1);
printf("cPtr2 Stored:%c Point:%x Memory:%x\n", cPtr2, *cPtr2, &cPtr2);问题是,每次我运行它,它存储一个不同的字符,总是指向'41‘。我做错什么了?
发布于 2018-04-27 16:25:03
你把传递给printf的内容搞混了。以下是您要寻找的内容:
printf("cPtr1 Stored:'%c' Point:%p Memory:%p\n", *cPtr1, (void*)cPtr1, (void*)&cPtr1);
printf("cPtr2 Stored:'%c' Point:%p Memory:%p\n", *cPtr2, (void*)cPtr2, (void*)&cPtr2);如您所见,cPtr1和cPtr2都指向同一个字符。此外,这两个指针是相同的。然而,指针本身在内存中占据单独的位置。
对变动的解释:
*cPtr1以使用%c打印%p打印指针(void*)。发布于 2018-04-27 16:24:56
问题是,在“存储:”之后打印地址:
ch = 'A';
cPtr* = &ch;
printf("%x",cPtr); // Printing the pointer value(the address of the stored char).
printf("%c",*cPtr); // Printing the value which the pointer points to(dereferencing).
printf("%x",&cPtr); // Printing the address of the pointer itself.https://stackoverflow.com/questions/50066547
复制相似问题