String pointer and char pointer Array

Source: Internet
Author: User

I. String pointer

A string is a special char array. A pointer to a char array is a string pointer. Like normal pointers, string pointers must be defined before use. The difference between a string and a char array is the length. The character is automatically appended with a length '\ 0' at the end, and the length of a char array is the number of characters. The string length is the number of characters plus 1. Example:

#include<iostream>using namespace std;int main(){    char str[]="hello world";    char *p=str;    cout<<str<<endl;    cout<<p<<endl;    cout<<*p<<endl;    system("pause");    }

2. Char pointer Array

The element of the pointer array is a pointer. Similar to a normal pointer, a pointer array must be assigned a value before use. Otherwise, it may point to meaningless values, which is dangerous. Take the char pointer array as an example.

int main(){    char *p[5]={"abc","def","ghi","jkl","mno"};    for(int i=0;i<5;i++)    puts(p[i]);    system("pause");    }

For int type data, see the following:

# Include <iostream> using namespace STD; int main () {int A = 1, B = 2, c = 3; int * P [] = {& A, & B, & c}; // cannot be written as int * P [] = {1, 2, 3}. This is invalid. Because p is first combined with [], it is a pointer array, and the data element of the array is int type pointer, not int type data. For (INT I = 0; I <3; I ++) cout <p [I] <Endl; // print out the address (pointer) system ("pause ");}

3. Compare the array names and addresses of int and char Arrays

#include<iostream>using namespace std;int main(){    int a[]={1,2,3};    char b[]={'a','b','c'};    cout<<a<<endl;    cout<<&a<<endl;    cout<<b<<endl;    cout<<&b<<endl;    system("pause");    }

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.