Pointers and Strings
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
上一篇: C和指针:第十一章:动态内存分配
下一篇: C和指针第十一章 动态内存分配
推荐阅读
-
Pointers and Strings
-
C Primer Plus ---- Chapter 11 ----Character Strings and String Functions ---- 2.字符串输入函数
-
6.10 Pointers and const
-
Leetcode 116. Populating Next Right Pointers in Each Node(容易理解的解法)
-
NOTES - Array of Pointers to Strings / 指向str array的多级指针数组
-
two pointers 双针法
-
4.6 two pointers
-
Move Zeroes——Two Pointers
-
two pointers
-
51nod 1495 中国好区间【2-pointers】