• c/c++指针常见错误


    #include <bits/stdc++.h>
    using namespace std;
    void f(char *str)
    {
        char *s = str;
        str[0] = '0' //error str是指向常量的指针,只能读取不能修改,如果str是malloc过则可以修改
        s[1] = '1'; //同上error
        cout<<s<<endl;
    }
    int main()
    {
        char *s = "We Are Happy.";
        f(s);
        puts(s);
        return 0;
    }

    #include <bits/stdc++.h>
    using namespace std;
    void f(char *str)
    {
        char *s = str;
        s[0] = 'a', s[1] = 'b', s[2] = 'c', s[3] = '';
        str = s;
    }
    int main()
    {
        char s[] = "We Are Happy.";
        f(s);
        puts(s); //abc
        return 0;
    }

    #include <bits/stdc++.h>
    using namespace std;
    void f(char *str)
    {
        char *s = (char *)malloc(sizeof(char)*100);
        s[0] = 'a', s[1] = 'b', s[2] = 'c', s[3] = '';
        str = s; //局部变量不会影响主函数
    }
    int main()
    {
        char s[] = "We Are Happy.";
        f(s);
        puts(s);    //We Are Happy.
        return 0;
    }

    #include <bits/stdc++.h>
    using namespace std;
    void f(char *str)
    {
        char *s = (char *)malloc(sizeof(char)*100);
        s[0] = 'a', s[1] = 'b', s[2] = 'c', s[3] = '';
        strcpy(str, s); //将s内的元素赋值给str,改变的不是指针是指针指向的值
    }
    int main()
    {
        char s[] = "We Are Happy.";
        f(s);
        puts(s);    //abc
        return 0;
    }
  • 相关阅读:
    wsdl和soap(简单使用TCPMon工具)03
    Django-7
    Django-6
    Django-5
    Django-4
    Django-3
    Django-2
    Django-1
    python_控制台输出带颜色的文字方法
    python网络编程
  • 原文地址:https://www.cnblogs.com/lesroad/p/10422275.html
Copyright © 2020-2023  润新知