【发布时间】:2014-01-19 20:09:22
【问题描述】:
我需要回答这个问题来测试这个:
练习 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);
}
这是我的输出:
我不知道为什么将字符串拆分为 From whence co 以及为什么其余文本(如您所见)没有意义。
我使用的是 Xcode 5.02
【问题讨论】:
标签: c++ c coding-style programming-languages