• C/C++ 0xC0000005: 写入位置 0xcccccccc 时发生访问冲突


      看下面的一段代码。复制字符串

    #include<stdio.h>
    void str_cpy( char *s,char *t)
    {
     while((*s=*t)!='\0')
     {
      s++;
      t++;
     }
     *s='\0';
    }
    void main()
    {
     char *a="I am a teachar.";
     char *b="you are a student.";
     str_cpy(a,b);
     printf("%s\n",a);
    }

     但是一运行就会报错,访问内存错误。为什么?

    因为:char *a="I am a teachar."; 字符串存储在常量区。只能读,不能写。

    怎么改呢?

    指针改成数组,如下:

     char  a[80]="I am a teachar.";

      改后,字符串存储在栈区。就可以改了,程序正常输出。

     

     再看下面一个简单例子:

    #include<stdio.h>
    #define MAX_NAME 5
    typedef char* VertexType; int main() { VertexType a; scanf("%s",a); printf("%s",a); }

    运行还是错误。应改为:

    typedef  char VertexType[MAX_NAME]; //数组类型

    或者先跟指针类型分配空间:

    typedef  char* VertexType;

    a=(VertexType)malloc(80);

    程序正确运行。

    注意数组不能写成:

    typedef  char[MAX_NAME]  VertexType; 是错误的,

    必须把维度写在名字后面。

     

  • 相关阅读:
    Codeforces
    Codeforces
    SCUT
    Codeforces
    Codeforces
    poj 2229 Sumsets(类似于n的m划分)
    poj 1742 Coins(多重背包)
    hdu 2159FATE(完全背包)
    NOIP 普及组 2014 比例简化
    2018.10.2浪在ACM 集训队第三次测试赛
  • 原文地址:https://www.cnblogs.com/youxin/p/2520674.html
Copyright © 2020-2023  润新知