我想學習C中的指針,並且已經通過了概念。我遇到了這個實驗問題,並試圖爲它寫一個解決方案。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
與字符'A'
,那麼我應該如何使指針變量ptr3
指向它?
這裏的節目,我wrote-
#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'用於空終止的字符串。你有一個字符。 – user2357112
「在C中指向一個字符的指針是什麼?」 *一個人物***。 –
爲什麼要將'sizeof(ptr1)'強制轉換爲'void *'? – user2357112