私は 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.
*/
ただし、プログラムをコンパイルすると、2 つの主要なエラー カテゴリがあります。
printf ステートメントのフォーマット プレースホルダーがすべて間違っているようです。私は、メモリ アドレスを %x または %p で出力できるという印象を受けました。しかし、私のプログラムでは、どちらもコンパイラの警告を生成しました。私は理解できませんでした - 以前のプログラムの一部で %p が警告なしに機能した理由と、ここで %x と %p の両方が機能しなかった理由。どのプレースホルダーがどのデータ型で機能するかについて、誰かが私を助けてくれますか?
もう 1 つの大きな問題は、ポインターを文字変数に割り当てることです。このプログラムを実行すると、プログラムの 3 番目の 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;
}
どんな助けでも大歓迎です。ありがとうございました。