[英]Pointer to pointer gives segmentation fault?
這是代碼
int main
{
char s[]="prady";
char **p;
p=(char **)&s;
printf("%u %u\n",p,*p);
printf("%u %u\n",&s,s);
printf("%s\n",s);
printf("%s\n",&s);
printf("%u %u\n",s+1,&s+1);
printf("%s\n",p);
printf("%s\n",*p);
}
O / P:
3217062327 1684107888
3217062327 3217062327
prady
prady
3217062328 3217062336
prady
Segmentation fault
我懷疑如下
地址如何與s和&s相同?
如果兩者相同,那么在向它添加1時它們的顯示方式有何不同?
我怎么在* p中出現分段錯誤?
首先,數組不是指針。 指針不是數組。 數組衰減成指針。
1.How both the address is same of s and &s?
char s[]="prady";
--------------------------
s: | p | r | a | d | y | \0 |
--------------------------
數組s
是要求留出6個字符的請求。 換句話說,在s
有6個字符。 's`是一個“東西”,它沒有任何意義,只是。
char *ptr = "prady";
------ --------------------------
|*ptr| --> | p | r | a | d | y | \0 |
------ --------------------------
指針ptr
請求保存指針的位置。 指針可以指向任何字符或任何字符串文字(連續字符)。
另一種思考方式:
int b; //this is integer type
&b; //this is the address of the int b, right?
int c[]; //this is the array of ints
&c; //this would be the address of the array, right?
所以這是可以理解的:
*c; //that's the first element in the array
這行代碼告訴你什么? 如果我尊重c,那么我得到一個int。 這意味着普通c就是一個地址。 因為它是數組的開頭,所以它是數組的地址,因此:
c == &c;
2. If both are same then how they show different when adding 1 to it.
從我對#1的回答,我假設你明白為什么他們不一樣。 那么為什么你會得到不同的價值觀? 看看你得到的價值觀:
s = 0x3217062327
s+1 = 0x3217062328 // It's 1 bigger, why? Because a char takes 1 byte, s holds chars
// so s (address of a char) + 1 (sizeof char) gives you one more than s
&a + 1 //This is adding 1 (sizeof array) which is bigger than the size of a char
3. How I got segmentation fault in *p.
我想你可以從我之前的兩個答案得到這個......但是:
當你進行類型轉換時,你告訴編譯器“我知道的比你好,所以只需要讓這兩個工作”。 當你發生段錯誤時......那是因為你真的不知道更好。
在你的情況下,s不是指針。 這是一個陣列!
一個小小的改變將解決一個問題:
char *s = "prady";
1.地址與s和&s相同。
s
是一個字符數組。 但是,數組被轉換為指針,除了少數情況:當它們用於初始化數組時(例如:你的char s[]="prady";
line),當它們是一元&
運算符的操作數時(很多)你的代碼中的案例),以及它們是sizeof
運算符的操作數。
2.如果兩者相同,則在向其添加1時它們的顯示方式不同。
她們不一樣。
2.如何在* p中出現分段錯誤。
p
包含"prady"
的地址。 *p
包含"prady"
。 嘗試使用"prady"
就好像它是字符串的地址一樣會導致段錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.