首页 > 编程语言 > 详细

c/c++指针常见错误

时间:2019-02-23 13:35:52      阅读:161      评论:0      收藏:0      [点我收藏+]

#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] = \0;
    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] = \0;
    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] = \0;
    strcpy(str, s);
}
int main()
{
    char s[] = "We Are Happy.";
    f(s);
    puts(s);    //abc
    return 0;
}

 

c/c++指针常见错误

原文:https://www.cnblogs.com/lesroad/p/10422275.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!