我正在尝试学习 C 中的指针,并且已经了解了这些概念。我遇到了这个实验室问题,并试图为它写一个解决方案。
/* p1.c
Write a short C program that declares and initializes (to any value you like) a
double, an int, and a char. Next declare and initialize a pointer to each of
the three variables. Your program should then print the address of, and value
stored in, and the memory size (in bytes) of each of the six variables.
Use the “0x%x” formatting specifier to print addresses in hexadecimal. You
should see addresses that look something like this: "0xbfe55918". The initial
characters "0x" tell you that hexadecimal notation is being used; the remainder
of the digits give the address itself.
Use the sizeof operator to determine the memory size allocated for each
variable.
*/
但是,当我编译程序时,我有两大类错误 -
我的 printf 语句的格式占位符似乎全错了。我的印象是内存地址可以用 %x 或 %p 打印。但是在我的程序中,两者都生成了编译器警告。我不明白——为什么在我以前的一些程序中,%p 没有任何警告就可以工作,为什么 %x 和 %p 在这里都不起作用。有人可以帮助我了解哪些占位符适用于哪些数据类型吗?
另一个主要问题是分配一个指向字符变量的指针。当我运行这个程序时,我在程序的第三个 printf 语句中遇到了分段错误。我不知道为什么会这样-
如果我是正确的,这样的声明——
char array[]="Hello World!"
和char *ptr=array
将字符指针变量设置ptr
为指向数组变量的第一个元素array
。因此,理想情况下,*ptr
将指示'H'
,*(ptr+1)
将指示'e'
等等。
遵循相同的逻辑,如果我有一个var3
带有 char的字符变量'A'
,那么我应该如何使指针变量ptr3
指向它?
这是我写的程序-
#include<stdio.h>
int main()
{
int var1=10;
double var2=3.1;
char var3='A';
int *ptr1=&var1;
double *ptr2=&var2;
char *ptr3=&var3;
printf("\n Address of integer variable var1: %x\t, value stored in it is:%d\n", &var1, var1);
printf("\n Address of double variable var2: %x\t, value stored in it is:%f\n", &var2, var2);
printf("\n Address of character variable var3: %x\t, value stored in it is:%s\n", &var3, var3);
printf("\n Address of pointer variable ptr1: %x\t, value stored in it is:%d\n", ptr1, *ptr1);
printf("\n Address of pointer variable ptr2: %x\t, value stored in it is:%f\n", ptr2, *ptr2);
printf("\n Address of pointer variable ptr3: %x\t, value stored in it is:%s\n", ptr3, *ptr3);
printf("\n Memory allocated for variable var1 is: %i bytes\n", sizeof(var1));
printf("\n Memory allocated for variable var2 is: %i bytes\n", sizeof(var2));
printf("\n Memory allocated for variable var3 is: %i bytes\n", sizeof(var3));
printf("\n Memory allocated for pointer variable ptr1 is: %i bytes\n", (void *)(sizeof(ptr1)));
return 0;
}
任何帮助将不胜感激。谢谢你。