String processing always reminds yourself to manually add ' + ' at the end

Source: Internet
Author: User

Words do not say, we all understand that the string is the end of the ' s ', but it is today programmed to forget to add ' to ', the result of a waste of time debugging to find, embarrassed dead.

First through a piece of code to see, forget to add ' to ' will cause what difficult to find trouble it

1#include <iostream>2#include <string>3 using namespacestd;4 intMain ()5 {6     Char*p;7     Char*q="AB";8p=New Char[2];9Cout<<strlen (P) <<Endl;Tencout<<sizeof(p); One     return 0; A}

Running Result: 16,4

1, clearly assigned to p two bytes strlen (p) Why did it become 16? Don't worry, let's go inside the strlen () function.

int strlen (constchar * str) {          int0;            while (*str++ )                   + +length          ; return (length);}

The original strlen () is based on ' s ' to determine whether to the end of the string, and regardless of whether it has crossed the line, and the program runs at the time of the P pointer after the 16th (this is a random value according to different circumstances) A byte has a 0, so it is considered to be 16.

2. Why is sizeof (p) 4? Needless to say, p is a pointer, the sizeof pointer is a fixed value of 4 (64bit system is 8), do not understand please see my previous write about sizeof blog

3, since the use of sizeof and strlen method can not see how many bytes assigned to p, that single-step debugging always see? The answer is no, let's take a look

In short, the programming encountered in the string must be remembered at the end of the manual add '! '!!!! Remember, remember.

String processing always reminds yourself to manually add ' + ' at the end

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.