zoukankan      html  css  js  c++  java
  • strcpy之段错误

    对c下的指针总有一种畏惧感,动不动就出现各种错误,先看一段程序吧:

    #include   <stdio.h> 
    #include <string.h>
    int main(void)
    {
    char *buf;               //定义char指针
    char *string = "hello ";       //指向常量数据区的“hello”字符串
    buf = string;               //将指向常量的指针赋值

    printf("buf=%s\n ", buf);
    strcpy(buf, "world");          //试图将常量数据区的 "world"字符串拷贝给指向常量数据区的buf
    printf("buf=%s\n", buf);
    return 0;
    }

    于是在strcpy处,出现了段错误 Segmentation fault

    解决办法:

    一、buf没有空间,   应该用malloc分配空间

    buf = malloc(4);

    二、改变 string为:

    char string[ ] = "hello";

    这样,string是指向数组的指针,赋值后,buf也是指向数组的指针,再次调用strcpy时,就把“world”复制到数组中了!

    三、可以直接赋值:

    buf = "world";

    小结:指针只存贮了一个地址,想把整个字符串复制给他,必须手动分配内存空间,或存放于数组之中。

  • 相关阅读:
    1063. Set Similarity
    A1047. Student List for Course
    A1039. Course List for Student
    最大公约数、素数、分数运算、超长整数计算总结
    A1024. Palindromic Number
    A1023. Have Fun with Numbers
    A1059. Prime Factors
    A1096. Consecutive Factors
    A1078. Hashing
    A1015. Reversible Primes
  • 原文地址:https://www.cnblogs.com/xiangzi888/p/2359521.html
Copyright © 2011-2022 走看看