查找故障或错误 [英] Find the fault or error
问题描述
你能找到什么是错用下面的code?
Can you find what is wrong with the following code?
int main(){
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
我预计它会打印空间后跟一个字符串!
I expected it will print space followed by a string!
推荐答案
下面是使用方法 ++ * P ++
:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
char *p = "My test string", p1[15];
strncpy(p1, p, 14);
p1[14] = 0;
p = p1;
while (*p != 0) {
printf("%c", ++*p++);
}
}
需要注意的是 P1
是内存中的数组(通常)在栈中分配,而 P
(通常
)的指针,只读存储器,它上面的code移动到指向 P1
,而不是(通常)其中字符串驻留只读位置。某些操作系统和/或编译器会出现其他的行为,但这是建立了现代操作系统为prevent某些类别的病毒保护机制之一。
Note that p1
is an array of memory (usually) allocated on the stack, whereas p
is (usually) a pointer to read only memory, which the above code moves to point to p1
instead of the (usually) read only location where the string resides. Some operating systems and/or compilers will exhibit other behavior, but this is one of the protection mechanisms built into modern OSs to prevent certain classes of viruses.
这篇关于查找故障或错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!