Problems with output character pointers and string pointers in C and C + +

Source: Internet
Author: User

Let's start by figuring out that there are no strings in C, so there are two forms of string manipulation: You can use a character pointer, or an array of strings ( Here's the pointer variable c, where the system will reallocate memory.)

C Program Example:

1 #include <stdio.h>
2
3 int Main ()
4 {
5 char *a= "Hello";
6 char b[]={' l ', ' I ', ' n ', ' U ', ' X '};
7 Char *c=&b[1];
8
9 printf ("%c\n", *a);
Ten printf ("%s\n", a);
printf ("%s\n", c);
printf ("%s\n", b);
printf ("%c\n", *c);
return 0;
15}

The following results are performed:

[Email protected] ~]$./CP
H
Hello
Inux
Linux
I
4



When you dereference A, the output pointer points to the first character "H", while printf ("%s\n", a) does not output the address of C because it specifies the format of the output string, but rather the string "hello". printf ("%d\n", a) outputs the address of the decimal point C.

Examples of C + + programs:

 1 #include <iostream>
  2 #include <stdio.h
  3 #include <string.h>
  4 using namespace std;
  5
  6 int main ()
  7 {
  8     string s = "string";
  9     String *p=&s;
 10     char * c= "Hello";
 11     cout<<*c<<endl;
 12     cout<< c<<endl;
 13     cout<<s<<endl;
 14     cout<<*p<<endl;
 15     cout<<p<<endl;
 16     return 0;    
 17}
cout output is automatically determined by the format of the output, and there is a string To represent the string, *p the entire string, and p outputs the first address of the string. When COUT<<C is automatically determined as the output string, * C to the first character "H" of the output string when the C is dereferenced.

Execution result: [[email protected] ~]$./test
H
Hello
String
String
0x7fff97664730

Problems with output character pointers and string pointers in C and C + +

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.