2015-08-27 135 views
3

考慮下面的程序:(見現場演示here混淆指針減量使用C

#include <stdio.h> 
int main(void) 
{ 
    char c[]={'s','h','r','e','y','a','\0'}; 
    char *ptr=c; 
    for(int i=0;i<6;i++) 
     printf("%c",ptr[i]); 
    printf("\n"); 

    char (*s)[7]; 
    s=&c; 
    for(int i=0;i<6;i++) 
     printf("%c",(*s)[i]); 
    printf("\n"); 

    ptr=&c[5];  // ptr points to 6th char of string 
    for(int i=5;i>=0;i--) 
     printf("%c",ptr[i]); 
} 

程序是不是給預期結果。我得到的結果是:

SHREYA

SHREYA

一個

,但如果我寫的最後一環像以下正常工作。

for(int i=5;i>=0;i--) 
    printf("%c",c[i]); 

我在這裏瞭解指針錯誤嗎?當我在last for循環中寫printf("%c",ptr[i]);時,爲什麼只有最後一個字符作爲輸出。

+0

在程序的ptr = &c[5];不需要 – venki

+4

順便說一句:代替'炭C [] = {'s','h','r','e','y','a','\ 0'};'你可以寫'char c [] =「shreya」;'這是嚴格的一樣。 –

回答

6

當你做了分配

ptr=&c[5]; 

你發ptr指向數組的元素fifth,即a。現在在循環內您正在打印ptr[i]

讓我們從循環的開始處開始,看看它打印的是什麼。

*(ptr+5),這超出了陣列c[]

{'s','h','r','e','y','a','\0'}; 
^^^^^^^^^^^ 
    0 1 2 3 4 5 6 G G G G //G -> Garbage 
        ^    ^
        ptr    (ptr+5) 

與之相似,這種情況持續下去,直到i0,最後一次迭代,即*(ptr+0)。在其上打印a

+1

你正在計數0 - > 1 - > 3 - > 4 ... 2是哪裏? –

+0

編輯。 thanx .. – Haris

3

隨着ptr=&c[5];您的指針指向「A」

第一循環將指向UB因爲'a'+5等將成爲地址。

你需要的是:

ptr=&c[5]; 
for(int i=5;i>=0;i--){ 
    printf("%c",*ptr); 
    ptr--; 
} 

或者

ptr=c; 
for(int i=5;i>=0;i--){ 
    printf("%c",ptr[i]); 
} 

許多其他的方式來做到這一點..

5

分配ptr=&c[5];你做出ptr持有的第5個元素的地址字符串。

如果您想要訪問前面的元素,您需要一個負指數來退回字符串。

ptr=&c[5];  // ptr points to 6th char of string 
for(int i=4;i>=0;i--) 
    printf("%c",ptr[-i]); 

或者

ptr=&c[5];  // ptr points to 6th char of string 
for(int i=-4;i<=0;i++) 
    printf("%c",ptr[i]); 

請亦認爲第五元件被移位的4個位置(因爲第一個是在偏移0,從0到4計數有5個符號)。

其它作品,因爲數組c總是指向元素0

3

問題的地址是這部分代碼:

ptr=&c[5];  // ptr points to 6th char of string 
for(int i=5;i>=0;i--) 
    printf("%c",ptr[i],i); 

更改上述給:

ptr=&c[5];  // ptr points to 6th char of string 
for(int i=5;i>=0;i--) 
    printf("%c",ptr[i-5],i); 

ptr[i]你能帶你一個未定義的參考,因爲ptr+5,ptr+4等可能不能訪問ible,他們不指向陣列。

一種更好的方式將是簡單地在陣列的底部指向和打印這樣的:

ptr=&c[0];  // ptr points to the base address of the char array 
for(int i=5;i>=0;i--) 
    printf("%c",ptr[i]); 
+0

你的代碼是越野車。糾正它。 – Destructor