我正在尝试学习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'
以此类推。
按照相同的逻辑,如果我有一个带有字符'A'
的字符变量var3
,那么我应该如何使指针变量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;
}
任何帮助都将不胜感激。谢谢。
%c
用于字符。%s
用于以 null 结尾的字符串。你有一个字符。 - user2357112sizeof(ptr1)
强制转换为void *
? - user2357112