首页 > 解决方案 > 如果在循环中,指针是否会自行移动到数组中的下一行?

问题描述

在我的程序中,pointer 是文件第一行文本的地址,pointer_ew 是文件第三行文本的地址。我正在尝试在不同文件的地址之间打印文本。我想知道指针在遇到新行或空字符时会自行移动到下一行吗?如果不是,请解释以下代码会导致什么样的错误?

 int m=row_ew[pick_ew]; /* m is equal to 2, which is the address to the first element of the third row in the array*/ 
 int n=pos_ew[pick_ew]; /* n is equal to the index of the word in the third line to increment the pointer position to the address of the first character of the word*/

 pointer_ew=file[m]+n+strlen(endword); /* Add the length of the word to increment the pointer to the end of the word*/

 pointer=file[i]; /*i is 0, address to the first element of the first row in the array*/

 while(pointer!=pointer_ew)
 {
   fputc(*pointer,outfile);
   pointer++;
 }

它工作正常,但我没有看到我试图从中复制的文件中的随机字符。但我确实在我要复制到的文件中看到它。在该行的开头,在输出文件中,我看到一些额外的随机字符 (<´ri ) 以及复制的文本。

标签: c

解决方案


在文本文件中,“换行符”是常规字符,\n在类 Unix 系统中为 10 ( ),\r在旧 Mac 上为 12 ( \r\n),在 Dos 或 Windows 上为 10 12 ( )。

这应该逐个字符地复制文件,无论你有什么,直到你点击结束指针(注意,我不确定你在做什么,但如果pointer_ew不指向你原始字符串的一部分[1] ,您的程序将尝试输出 RAM 中的任何内容,直到操作系统以段错误终止您的程序)。

[1]。如,如果您没有pointer根据(如)定义 pointer_ew pointer_ew = pointer+5。如果pointer_ew 指向另一个字符串,你会得到一个Segmentation Fault。


推荐阅读