C + + arrays and pointers

Source: Internet
Author: User

Let's look at the following code:

#include <iostream> #include <stdio.h> #include <string>using namespace Std;int main () {int time[] = { 1,2,3};int *q; q = time;cout<<*q<< "" <<q<<endl;char arr[]= "Hello World"; string *p;string str[] = {"Linux", "Unix"};p = str;cout<<*p<< "" <<p<<endl;char* pc;pc = arr;cout<<arr<< "" <<*pc<<endl;cout<<pc<<endl;string s = "Linux"; string *ps;ps = &s;cout<<ps<<* Ps<<endl;return 0;}


Here is the result of the operation:

1 0x7fff6de21a20
Linux 0x7fff6de21a00
Hello World H
Hello World
0X7FFF6DE219F0 Linux
Explain:

I've always been a little puzzled by the pointers. So when it's okay to write this code specifically, the code is not difficult. But it's very helpful for me to know pointers and data.

Examples of time,str and s of all the output, according to the description in the book, it is easy to determine the output of the data. The only thing that confuses me is char* and char[].

In C and C + + if the direct assignment char* p= "Hello World", is equivalent to char arr[]= "Hello World"; p = arr. Here if you do not specifically declare "Hello World" as a string, it is considered a character array.

P points to the first address of the array. Output *p, which is the first character of the output. If you output p, the entire string is printed. This is the difference between the char* and non-char pointers I know.





C + + arrays and pointers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.