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] = '\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); //将s内的元素赋值给str,改变的不是指针是指针指向的值
}
int main()
{
    char s[] = "We Are Happy.";
    f(s);
    puts(s);    //abc
    return 0;
}

 

转载于:https://www.cnblogs.com/lesroad/p/10422275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值