The distinction between string constants and character arrays

Source: Internet
Author: User

First, let's take a look at the program, which is about the implementation of the String function strcat () function:

#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#define MAX
Char *my _strcat (char *dest, const char *src)
{
    char * ret = dest;
    ASSERT (dest);
    ASSERT (SRC);
    while (*dest)
    {
        dest++;
    }

    while (*dest = *src)
    {
        dest++;
        src++;
    }
    return dest;
}
int main ()
{
    char Arr1[max] = "ABCD";
    Char *arr2 = "ABCD";
    My_strcat (arr1, arr2);
    printf ("%s\n", arr1);
    System ("pause");
    return 0;
}

Here we have a question:

Char Arr1[max] = "ABCD";
    Char *arr2 = "ABCD";

This two is why this should be initialized.

In fact, the first line is initialized with a character array.

Char Arr1[max] = "ABCD";

Although he looks like a string constant, it's not, he's just another way of initializing the list. He is differentiated according to the context in which they are located, and when used to initialize a character array, he is an initialization list, and elsewhere, he represents a string constant

And the second sentence:

Char *arr2 = "ABCD";

The initialization here is a string constant.

These two initializations look very much alike, but they have different meanings, the former initializing the elements of a character array, and the latter being a true string constant. This pointer variable is initialized to the storage location that points to the string constant.

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.