指向字符的指针在C中指向什么?

Man*_*iri 5 c pointers char char-pointer

我正在尝试学习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. 
*/
Run Code Online (Sandbox Code Playgroud)

但是,在编译程序时,我有两大类错误 -

  1. 我的printf语句的格式占位符似乎都是错误的.我的印象是内存地址可以使用%x或%p打印.但在我的程序中,都生成了编译器警告.我不明白 - 为什么在我之前的一些程序中,%p在没有任何警告的情况下工作,以及为什么%x和%p在这里都不起作用.有人可以帮我解决哪些占位符使用哪种数据类型?

  2. 另一个主要问题是分配指向字符变量的指针.当我运行这个程序时,我在程序的第三个printf语句中得到分段错误.我不知道为什么会这样 -

如果我是对的,这样的声明 -

char array[]="Hello World!"
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激.谢谢.

M.M*_*M.M 6

除非printf说明符char%c (不是%s),否则所有这些都是正确的.

遵循相同的逻辑,如果我有一个var3带有char 的字符变量'A',那么我应该如何使指针变量ptr3指向它?

请参阅您的代码以获得答案!

Howwver你在其他printf语句中有一些类型不匹配.在你用的最后一个%i(void *),我不确定你在想什么.

要打印的结果,sizeof使用%zu(不转换为void *),这适用于您的最后四个printf语句.

%x用于打印地址的其他语句中.这是错误的(你的做法也是错误的).您应该使用%p打印地址.

从技术上讲,你也应该将地址转换为void *,虽然在现代系统中,所有指针都具有相同的大小和表示,所以你可以逃避不做.

  • `%zu`是在1999年添加的,一些参考资料尚未赶上目标(有些编译器*咳嗽MSVCCcough*需要很长时间才能赶上) (3认同)