2014-01-19 36 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?