我正在做 C 编程作业。
#include <stdio.h>
typedef struct JustArray {
char *x;
} JustArray;
int main()
{
JustArray Items[12];
char *d = "Test";
Items[0].x = (char *) &d;
printf("Pointer: %p\n", &d);
printf("Address: %u\n",&d);
printf("Value: %s\n", d);
/*------------------------------------*/
//Knowing address of d from above, print value stored in it using Items[0].x. Cannot use &d, *d, or d.
char *ptr;
ptr = Items[0].x;
printf("%p\n", Items[0].x);
printf("%p\n", &ptr);
printf("%s\n", ptr);
return 0;
}
ptr 的输出也需要是“Test”,但它向我显示了奇怪的字符。任务是找到一种方法来使用 Items[0].x 中的地址信息并在控制台中打印其值“Test”。我找不到办法......
最佳答案
请记住,指针的值是一个地址。指针的内容(即它的取消引用、指向的值、由它寻址)是位于另一个位置的值(具有所指向的类型)。因此,int* 将另一个变量(int 类型)的地址作为值存储在另一个地址。请注意,C 中的每个原始变量都是存储在某个地址中的数据的名称。
int p = 1;
上面的p是一个int类型的var。它的值是 1,该值直接由 p 给出(因此 p == 1)。 p有一个可以用&p访问的地址(比如0x11111)(所以&p == 0x11111)。因此,p 是一个变量的名称,其值为 int (1),其地址为 0x11111(由 &p 给出) )。这意味着值1(这是一个int)存储在地址0x11111中。
int* q = 0x22222;
上面的q是一个int*类型的var(指向int的指针,意思是“指向类型的var的地址” int”)。 q 有一个地址作为值(在本例中为 0x22222),该值直接由 q 给出(因此 q == 0x22222 )。 但是q也有一个地址(比如0x33333),可以使用&q访问它(所以 &q == 0x33333)。因此,q 是一个变量的名称,其值是 int 的地址(0x22222,由 q 给出) ),其地址为 0x33333(由 &q 给出)。基本上,值0x22222(这是一个地址)存储在地址0x33333中。
您可以在 q 上使用前缀运算符 * 来取消引用它,即访问其内容,即存储在地址 0x22222 中的值>,这是q的值。所以基本上我们有:q==0x22222,&q==0x33333,和*q==[无论地址0x22222中存储的值是什么>]。现在考虑一下:
int* r = &p;
请记住,p 的值为 1(由 p 本身给出的 int)和地址 0x11111(由&p给出)。现在,我声明了一个名为 r 的指向 int 的指针,并使用 p (0x11111) 的地址对其进行了初始化。因此,r是一个指针,其值为地址(0x11111),但它也有一个地址(例如0x44444)。
指针前面的运算符*让我们可以访问作为其值的地址的值。所以*r会给我们1,因为1是存储在地址0x11111中的值,这是值r 的地址和 p 同时的地址。所以r==&p(0x11111==0x11111)和*r==p(1==1 )。
现在让我们回到您的代码。当你声明一个 char* 时,你已经有了一个指针,因此如果你将 %p 设置为所需的格式,那么它的打印将是一个地址,如果你设置,它的打印将是一个字符串%s 作为所需的格式。 (%s 使函数 printf 迭代内容,其起始地址是给定指针的值(当到达时停止) a '\0')。我修复了您的代码(为了便于阅读,对其进行了一些修改)。问题是您将指针的地址而不是指针本身发送到函数printf。
#include <stdio.h>
typedef struct justArray
{
char* x;
}
JustArray;
int main()
{
//d is a pointer whose content is an address, not a char 'T'
char* d = "Test";
printf("Pointer: %p\n", d); //print the address (no need for &)
printf("Address: %lu\n", (long unsigned) d); //print the address again as long unsigned)
printf("Value: %s\n", d); //print a string because of the %s
JustArray Items[12];
Items[0].x = d;
printf("%p\n", Items[0].x); //Items[0].x == d, so it prints the same address
char* ptr = Items[0].x;
printf("%p\n", ptr); //ptr == Items[0].x, so it prints again the same address
printf("%s\n", ptr); //prints the string now because of the %s
return 0;
}
该程序的输出将是:
Pointer: 0x400734
Address: 4196148
Value: Test
0x400734
0x400734
Test
关于C:给定已知的地址和类型,如何打印其中存储的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48390781/