前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pointers and Strings

Pointers and Strings

作者头像
青木
发布2018-05-28 15:45:19
3840
发布2018-05-28 15:45:19
举报
char flower[10] = 'rose';
cout<<flower<<"s are  red\n";

The name of an array is the address of its first element,so flower in the cout statment is the address of the char element containing the character. The cout object assumes that the address of a char is the address of a string,so it prints the character at that address and then continues printing characters until it runs into the null character(\0). In short,if you give cout the address of a character,it prints everything from that character to the first null character that follows it.

Note With cout and with most C++ expressions,the name of an array of char,a pointer-to-char,and a quoted constant are all interpreted as the address of the first character of a string. Caution When you read a string into a program-style string,you should always use the address of previously allocated memory.This address can be in the form of an array name or of a pointer that has been initialized using new. Use strcpy() or strncpy() ,not the assignment operator,to assign a string to an array.

code:

#include<iostream>
using namespace std;

int main(int argc, char const *argv[])
{
	
	char animal[20] = "bear";
	const char *bird = "wren";//bird holds address of string
	char *ps;

	cout<<animal<<" and ";
	cout<<bird<<endl;

	cout<<"Enter a kind od animal: ";
	cin>>animal;

	ps = animal;
	cout<<ps<<endl;
	cout<<"Before using strcpy(): "<<endl;
	cout<<animal<<" at " <<(int*)animal<<endl;
	cout<<ps<<" at "<<(int*)ps<<endl;

	ps = new char[strlen(animal)+1];
	strcpy(ps,animal);//copy string to new storage
	cout<<"After using strcpy():"<<endl;
	cout<<animal<<" at "<<(int*)animal<<endl;
	cout<<ps<<" at "<<(int*)ps<<endl;
	delete [] ps;
	return 0;
}

Output:

bear and wren
Enter a kind od animal: dog
dog
Before using strcpy(): 
dog at 0x7ffee1257b30
dog at 0x7ffee1257b30
After using strcpy():
dog at 0x7ffee1257b30
dog at 0x7ffa66d00000
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档