百科知识

为什么用devc++编译下面的代码,运行会提示内存不可写?#in

2011-06-15 20:24:21坐***
#include<stdio.h> #include<string.h> int main() { char *pch,ch; int n1,n2; printf("The first number:"); scanf("%s",pch); n1=strlen(pch); printf("The second number:"); scanf("%s",pch); n2=strlen(pch); printf("%d %d",n1,n2); }为什么用devc++编译下面的代码,运行会提示内存不可写?#includestdio.h#includestring.hintm?

最佳回答

  • 1 #include 2 #include 3 int main() 4 { 5 char pch[20],ch;//这里不能只声明指针, 指针没有明确的内存空间让你用, 需要明确的分配给内存 6 int n1,n2; 7 printf("The first number:"); 8 scanf("%s",pch); 9 n1=strlen(pch); 10 printf("The second number:"); 11 scanf("%s",pch); 12 n2=strlen(pch); 13 printf("%d %d",n1,n2); 14 } 如果就是要那样用的话可以在char *pch之后, 用malloc指定空间
    2011-06-15 22:23:19
  • 你都没将pch指针变量指向哪个地址,那它上哪有内存写呢?对吧
    2011-06-19 09:14:56
  • 一个程序加载到内存中开始运行的时候,称为进程,系统为每个进程分配一块空间,此为进程的虚拟地址空间,该虚拟地址空间又被划分为代码区,数据区,堆区,栈区(还有其他区域,这四块是程序员关注的主要区域),其中每个区都有读写权限,除了代码区外,其他三个区都是默认可读可写的,代码区是只读的。 你的程序报错说内存不可写只可能是未初始化的pch指向了代码区,或者pch指向的虚拟内存越界了(超过系统指定的进程空间) 改正错误的方法是将pch初始化,而初始化pch的方法有两种 1.char pch[BUFSIZE];//在栈中分配BUFSIZE个字节, 2.char *pch = malloc(BUFSIZE);//在堆中分配BUFSIZE个字节 其余代码不变
    2011-06-18 12:44:41
  •   #include #include int main() { char buf[1024],*pch; int n1,n2; pch = buf; printf("The first number:"); scanf("%s",buf); n1=strlen(pch); printf("The second number:"); getchar(); scanf("%s",buf); n2=strlen(pch); printf("%d %d",n1,n2); } %s--是字符串pch是char型指针。
       错误出在: 指针调用之前没有赋值。使用指针千万要注意这点。 因为没有赋值的指针所指向的空间不确定。你将内容写入不确定的地址肯定出错。 顺便说句C++里的String。C里面还是别用。有点怪怪的。 楼主加油了。
    2011-06-15 22:02:49
  • 很赞哦! (254)