首页 > 编程知识 正文

字符指针赋值给字符数组,字符型指针变量赋值的方法

时间:2023-05-03 22:30:45 阅读:21186 作者:2450

我今天在书上看例题,看了下面的代码。

# includeiostreamusingnamespacestd; int main () { char *p=NULL; p='计算机'; cout p endl; for(intI=0; i 8; I ) cout p[i]; cout endl; wile(p ) ) cout ) p; p; } cout endl; 返回0; }深色的C型码露出了脸。 我试图修改那个。

# includeiostreamusingnamespacestd; int main () { char p[]={}; p='计算机'; cout p endl; for(intI=0; i 8; I ) cout p[i]; cout endl; wile(p ) ) cout ) p; p; } cout endl; 返回0; }系统错误。 暴露了我的理解问题。

因为如果字符串常量显示在表达式中,则使用的值不是这些字符本身,而是存储这些字符的地址。 因此,可以将字符串指定给指向字符的指针。

此时的指针类似于字符数组的数组名称,不同的是该指针是可变的,数组名称指针是常量指针。 也就是说,修改后的代码是错误的,因为不能分配给常量。

所以我做了更大幅度的修改。

# includeiostreamusingnamespacestd; int main () charp ()='computer '; cout p endl; for(intI=0; i 8; I ) cout p[i]; cout endl; char *q=p; while(q ) ) cout ) q; q; } cout endl; 返回0; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。