2014-01-19 37 views
-1

我要回答這個問題,測試這種重用在C數組變量:如何使用指針

練習19-16:修復示例中的代碼,以便採樣變量的值while循環之前保存然後運行,然後恢復。 while循環完成後,向代碼中添加puts(sample)語句,以證明該變量的原始地址已被恢復。

**Example:** 
    #include <stdio.h> 

    int main() 
    { 
     char *sample = "From whence cometh my help?\n"; 

     while(putchar(*sample++)) 
      ; 
     return(0); 
    } 

我想檢查我的答案是正確的,可能是你能給出一個解釋,因爲我對指針和變量沒有清晰的認識。 這就是我的回答:

 #include <stdio.h> 

     int main() 
     { 
      char *sample = "From whence cometh my help?\n"; //This is my string 
      char StringSample[31]; 
      int index = 0; 

      while(sample[index] != '\0') //while the char is NOT equal to empty char (the last one) 
      { 
       index++; //increase the index by 1 
       StringSample[index] = sample[index]; //put the char "n" inside the stringSample // 
       putchar(*sample++); //write it to the screen 
      } 
      putchar('\n'); //A new line 

      //to put the entire string on screen again 
      for (index=0; index<60; index++) 
      { 
       putchar(StringSample[index]); 
      } 
      return(0); 
     } 

這裏是我的輸出:

enter image description here

我不知道爲什麼字符串它拆分到From whence co爲什麼文本的其餘部分,即正如你所看到的,沒有任何意義。

我使用的Xcode 5.02

回答

2

的問題是,您要引用您的sample變量索引以及指針。這會導致你錯誤的結果。

while(sample[index] != '\0') 
{ 
    index++; 
    StringSample[index] = sample[index]; // indexed access 
    putchar(*sample++);     // incrementing pointer sample. 
} 

你可以簡單地實現自己的目標爲

#include <stdio.h> 

int main() 
{ 
    char *sample = "From whence cometh my help?\n"; 
    char *ptr = sample; // Saving the value of sample 

    while(putchar(*sample++)) 
     ; 
    putchar('\n'); 

    sample = ptr;  // Restoring sample's value. 
    puts(sample); 

    return(0); 
} 
+0

由於是明確的,現在, –

1
char StringSample[31]; 
.... 
for (index=0; index<60; index++) 
{ 
    putchar(StringSample[index]); 
} 

你的陣列有31個細胞,但你迭代遠至60.上帝知道你可以訪問什麼。

1

你讓這種方式更復雜,它需要。只需將指針保存在另一個變量中,並在完成後將其複製回來。

#include <stdio.h> 

int main() 
{ 
    char *sample = "From whence cometh my help?\n"; 
    char *temp = sample; 

    while(putchar(*sample++)) 
     ; 

    sample = temp; 
    puts(sample); 
    return(0); 
} 

輸出:

From whence cometh my help? 
From whence cometh my help?