欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Pointers and Strings

程序员文章站 2024-02-29 18:18:28
...
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

转载于:https://my.oschina.net/u/1771419/blog/1634953